在 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/