react-router v6:获取当前路由的路径模式

新手上路,请多包涵

是否可以获取当前匹配路由的路径模式?例子:

 <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 许可协议

阅读 2k
1 个回答

我用 react-router v6 做了一个自定义钩子 useCurrentPath 来获取当前的路由路径,它对我有用

如果当前路径名为 /members/5566 我将得到路径 /members/:id

 import { matchRoutes, useLocation } from "react-router-dom"

const routes = [{ path: "/members/:id" }]

const useCurrentPath = () => {
  const location = useLocation()
  const [{ route }] = matchRoutes(routes, location)

  return route.path
}


function MemberPage() {
  const currentPath = useCurrentPath() // `/members/5566` -> `/members/:id`

  return <></>
}

参考

https://reactrouter.com/en/v6.3.0/api#matchroutes

原文由 Futian Shen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题