在React路由器3中我可以有这样的路径:
/root(/id/:id)(/di/:di)
那就匹配
/root
/root/id/1
/root/di/2
/root/id/1/di/2
完美。
我无法弄清楚如何在React Router 4中做到这一点。所有的例子都只做了一件事。
使用Express Route tester我可以提出类似
的路线/root/id/:id?/di/:di?
但那只会匹配
/root/id/1/di/2
有解决方法吗?
答案 0 :(得分:3)
在反应路由器v4中,您可以将正则表达式包含在()
内。所以这个正则表达式应该工作并匹配你给出的所有路径:/root(/id/|/di/):id*(/id/|/di/)?:di*
。在你给出链接的Express router Tester工具中,键 nt 出现了这个正则表达式但它确实有效,我在localhost上测试并且键工作得很好。
请注意,我在第一次捕获组后没有使用?
,即(/id/|/di/)
,因为如果我这样做,那么它将成为可选项,然后像/root/12
这样的路径也会匹配。
答案 1 :(得分:1)
在这里,我最终是如何做到的,这有点荒谬但是有效:
<Route
path="/root/:firstKey?/:firstId?/:secondKey?/:secondId?"
render={({ match: { params: { firstKey, secondKey, firstId, secondId } } }) => {
const params = { [firstKey]: firstId, [secondKey]: secondId }
return (<Whatever {...params} />)
}}
/>