react-router - 获取非精确路由匹配的路由参数

标签 react-router react-router-v4

在 react 路由器(4.1.2)中,我渲染了以下路由:

<Route path="/organisations/:organisationId/profiles" component={MapContainer} />

在我的 MapContainer 中,我通过 this.props.match.params.organizationId 获取了符合预期的organizationId

MapContainer 组件也会在任何子路线上呈现,例如 /organizations/:organizationId/profiles/:profileId

这按预期工作,但 match 属性不包含 profileId,仅包含 organizationId。这……有点道理,因为它是它为路线找到的第一个“匹配”。但是当 MapContainer 匹配不精确的路由时,有什么方法可以获取 :profileId 吗?

使用 exact 属性渲染两条不同的路线似乎适合我的用例:

<Route exact path="/organisations/:organisationId/profiles" component={MapContainer} />
<Route exact path="/organisations/:organisationId/profiles/:profileId" component={MapContainer} />

但不确定这是正确的方法。

对此的任何建议都会非常有帮助。

最佳答案

改用这个:

<Route path="/organisations/:organisationId/profiles/:profileId?" component={MapContainer} />

:profileId? 表示该参数是可选的。所以它匹配这两个路径:

/organisations/apple/profiles
/organisations/apple/profiles/1

关于react-router - 获取非精确路由匹配的路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825873/

相关文章:

javascript - React-Router/Redux - 动态同构路由

javascript - 如何仅在 setstate 之后渲染页面

javascript - React Router v4 的嵌套路由 - 解决方案

javascript - 将 props 传递给 react-router v4 中的路由器组件

javascript - React Router 嵌套路由不渲染

javascript - React 路由器部署后不起作用

reactjs - 检测react-router中后退按钮被按下

javascript - 使用 useRoutes 时如何将 props 传递给路由组件?

javascript - 以编程方式将路由注入(inject) JSX 路由器开关语句

reactjs - 以 URL 链接作为参数的 React 路由