簡體   English   中英

如何檢查路由是否與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使用的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM