gpt4 book ai didi

reactjs - React Router V4 仅允许 URL 中的某些参数

转载 作者:行者123 更新时间:2023-12-03 13:40:07 25 4
gpt4 key购买 nike

我正在使用 React Router V4 并且我有这个路由器的配置:

  <Router history={customHistory}>
<Switch>
<Route exact path={`/:lng?`} component={Page} />
<Route path={`/:lng?/firstUrl`} component={Page}/>
<Route path={`/:lng?/secondUrl`} component={Page}/>
<Route component={NoMatch} />
</Switch>
</Router>

lng 是可选语言参数,应与 ende 等模式匹配或不存在。例如应用程序使用这些路由:

www.website.com/en
www.website.com/en/
www.website.com/ - will load default lang
www.website.com - will load default lang
www.website.com/de
www.website.com/de/

此外,我还有其他组件,在其中定义函数的路由:

  <ModalRoute component={SomeURL} path={`/:lng?/SomeURL`} parentPath={`/${lang}/`} />
<ModalRoute component={SomeURL2} path={`/:lng?/SomeURL2`} parentPath={`/${lang}/`} />

因此,我希望实现的是,仅接受允许的语言代码(和空参数),而不接受的语言代码将被重定向到 NoMatch 组件。

这可能吗?如何实现?
非常感谢示例

最佳答案

您可以在路径中使用正则表达式。

对于具有指定选项的必需参数:

<Route path="/about/:lang(en|de)/" exact component={About}/>

对于可选参数:

<Route path="/about/:lang?/" exact component={About}/>

对于具有指定选项的可选参数

<Route path="/about/:lang(en|de)?/" exact component={About}/>

对于further reading

关于reactjs - React Router V4 仅允许 URL 中的某些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com