是否可以获取当前匹配路由的路径模式?例子:
<Route
path=":state/:city*"
element={
<Page />
}
/>
// Page.jsx
function Page() {
...
// usePathPattern doesn't actually exist
const pathPattern = usePathPattern(); // pathPattern = ":state/:city*"
...
}
我知道我可以使用 useMatch
来检查当前位置是否与特定路径模式匹配,但是组件必须知道路径模式是什么。
原文由 caseyjhol 发布,翻译遵循 CC BY-SA 4.0 许可协议
我用 react-router v6 做了一个自定义钩子
useCurrentPath
来获取当前的路由路径,它对我有用如果当前路径名为
/members/5566
我将得到路径/members/:id
参考
https://reactrouter.com/en/v6.3.0/api#matchroutes