在React router 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对此有解决方案吗?
发布于 2017-07-06 18:55:47
在react路由器v4中,您可以在()中封装您的正则表达式。所以这个正则表达式应该可以工作,并与您给出的所有路径相匹配:/root(/id/|/di/):id*(/id/|/di/)?:di*。在您提供链接的快速路由器测试器工具中,键wont显示此正则表达式,但它确实工作,我在本地主机上测试,键工作得很好。
请注意,我在第一次捕获组后没有使用?,即(/id/|/di/),因为如果我这样做了,那么它将成为可选的,然后像/root/12这样的路径也将被匹配。
发布于 2017-07-06 20:09:42
这是我最后是如何做到的,这有点可笑,但它是有效的:
<Route
path="/root/:firstKey?/:firstId?/:secondKey?/:secondId?"
render={({ match: { params: { firstKey, secondKey, firstId, secondId } } }) => {
const params = { [firstKey]: firstId, [secondKey]: secondId }
return (<Whatever {...params} />)
}}
/>https://stackoverflow.com/questions/44945063
复制相似问题