Reaction-路由器v6:获取当前路由的路径模式 [英] react-router v6: get path pattern for current route
本文介绍了Reaction-路由器v6:获取当前路由的路径模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<Route
path=":state/:city*"
element={
<Page />
}
/>
// Page.jsx
function Page() {
...
// usePathPattern doesn't actually exist
const pathPattern = usePathPattern(); // pathPattern = ":state/:city*"
...
}
我知道我可以使用useMatch
检查当前位置是否与特定路径模式匹配,但随后组件必须知道路径模式是什么。
推荐答案
在Route
的上下文中,您可以通过the docs中列出的几种方法获取path
。
我的问题略有不同,因为我需要path
之外的Route
,并得出了以下解决方案,该解决方案也适用于您:
import {
matchPath,
useLocation
} from "react-router-dom";
const routes = [ ':state/:city', ...otherRoutes ];
function usePathPattern() {
const { pathname } = useLocation();
return matchPath( pathname, routes )?.path;
}
这篇关于Reaction-路由器v6:获取当前路由的路径模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文