如何检查路由是否与 React-Router v4 的模式匹配?

How to check if route matches a pattern with React-Router v4?

如何在没有 RouteNavLink 组件的情况下使用 React Router v4 检查路由模式是否与当前路由匹配,或者如何编写自己的正则表达式来匹配路由?

例如,如果路由是 /users/5/friends/3/pets/10/edit,我希望能够检查路由是否匹配模式(如 RouteNavLink 使用的模式)。像这样:

const isEditFriendPetRoute = routeMatches('/users/:userId/friends/:friendId/pets/:petId/edit');

console.log(
  isEditFriendPetRoute 
    ? `Is editing friend's pet`
    : `Is not editing friends pet`
)
import { matchPath } from 'react-router-dom'

const match = matchPath('/users/123', {
  path: '/users/:id',
  exact: true,
  strict: false
})

如果 URL 与路径模式匹配,那么它将 return 一个对象,否则它将 return null。

从下一页检查 api https://reacttraining.com/react-router/web/api/matchPath