React Router 的多个参数 [英] Multiple params with React Router
问题描述
我使用 React 15.0.2 和 React Router 2.4.0.我想将多个参数传递给我的路线,但我不确定如何以最佳方式做到这一点:
I use React 15.0.2 and React Router 2.4.0. I want to pass multiple params to my route and I'm not sure how to do it in the best way:
<Route name="User" path="/user" component={UserPage}>
<Route name="addTaskModal" path="/user/manage:id" component={ManageTaskPage} />
</Route>
想要的是:
<Route name="User" path="/user" component={UserPage}>
<Route name="addTaskModal" path="/user/manage:id:type" component={ManageTaskPage} />
</Route>
推荐答案
正如@alexander-t 提到的:
As @alexander-t mentioned:
path="/user/manage/:id/:type"
如果你想让它们保持可选:
If you want to keep them optional:
path="/user/manage(/:id)(/:type)"
React 路由器 v4
React Router v4 与 v1-v3 不同,可选路径参数未在文档中明确定义.
相反,您被指示定义一个路径参数,path-to-regexp 明白.这允许在定义路径时具有更大的灵活性,例如重复模式、通配符等.因此,要将参数定义为可选参数,请添加尾随问号 (?).
Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).
因此,要定义可选参数,您可以:
So, to define optional parameters, you can do:
path="/user/manage/:pathParam1?/:pathParam2?"
即
<Route path="/user/manage/:pathParam1?/:pathParam2?" component={MyPage} />
然而,V4 中的强制参数仍然相同:
Whereas, The mandatory Parameters are still same in V4:
path="/user/manage/:id/:type"
要访问 PathParam 的值,您可以:
To access PathParam's value, you can do :
this.props.match.params.pathParam1
这篇关于React Router 的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!