使用React-Router路由OR路径
问题描述:
我路由的页面保持相同的组件结构,但其内容基于URL略有变化。当这个区域设置了我的路我目前使用的结构如下:使用React-Router路由OR路径
<Route path="/:focusPath/read/agree" component={ViewerLayout} />
<Route path="/:focusPath/read/neutral" component={ViewerLayout} />
<Route path="/:focusPath/read/disagree" component={ViewerLayout} />
<Route path="/:focusPath/speak/agree" component={ViewerLayout} />
<Route path="/:focusPath/speak/neutral" component={ViewerLayout} />
<Route path="/:focusPath/speak/disagree" component={ViewerLayout} />
然而,这似乎重复和过于复杂。尽管它按原样工作,但是我可以通过重塑它来完成这样的事情吗?
<Route path={"/:focusPath"+("/read"||"/speak")+("/agree"||"/neutral"||"/disagree")} component={ViewerLayout} />
我意识到语法都是错误的,但也许是简化了它使它工作的6行的东西?
答
这不推荐,但它应该适用于您的用例。你可以传递一个正则表达式到path
。这里有一个片段可以帮你找到正确的想法。
<Route path="/:focusPath/read/(/agree|neutral|disagree/)" component={ViewerLayout} />
我是垃圾在正则表达式,所以可能不会像现在这样工作,但你明白了。
甜!谢谢,我没有意识到我可以使用正则表达式! 如果你想要一些练习,或者只是想尝试一些工作,[RegEx101](https://regex101.com/)是在正则表达式中更好的工具。 ;) –
真棒我会检查出来。谢谢! –