如何在没有 Route
或 NavLink
组件的情况下使用 React Router v4 检查路由模式是否与当前路由匹配,或者编写我自己的正则表达式来匹配路由?
例如,如果路由是 /users/5/friends/3/pets/10/edit
,我希望能够检查路由是否匹配某个模式(比如使用的那个通过 Route
和 NavLink
)。像这样:
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 与路径模式匹配,则它将返回一个对象,否则将返回 null。
从以下页面检查api https://reacttraining.com/react-router/web/api/matchPath
关于javascript - 如何检查路由是否与 React-Router v4 的模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50805900/