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

React Router V4 allow only certain parameters in URL

我正在使用 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