首页 > 解决方案 > React-Router-Dom:我可以调用 `useParams()` 来获取 Route 之外的路径参数吗?

问题描述

我有一个简单的 JSX

<div>
  <Header />
  <Route exact path = "/:id" component={Home}/>
  <Route exact path = "/other/:id" component={Other}/>
</div>

在标题中包含 NavLinks,我希望它们包含以前提供的 ID,例如...

const id = useParams().id;
const root = `/${id}`;
const Other = `/other${root}`;
<NavLink to={root} activeStyle={activeStyle} exact className="bg-link">Home</NavLink>
<NavLink to={other} activeStyle={activeStyle} exact className="bg-link">Other</NavLink>

问题是useParams().id返回未定义,因为它不在路线本身内。我可以从那里访问这些信息吗?

我正在使用 redux,所以我想知道是否不必将其置于路由器中的 redux 状态。但是,我还不太擅长 redux,所以如果可能的话,我想要一个更直接的答案。

标签: reactjsreact-router-dom

解决方案


推荐阅读