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

Kuz*_*zma 1 reactjs react-router react-router-v4

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

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/
Run Code Online (Sandbox Code Playgroud)

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

  <ModalRoute component={SomeURL} path={`/:lng?/SomeURL`} parentPath={`/${lang}/`} />
  <ModalRoute component={SomeURL2} path={`/:lng?/SomeURL2`} parentPath={`/${lang}/`} />
Run Code Online (Sandbox Code Playgroud)

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

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

cow*_*azy 5

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

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

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

对于可选参数:

<Route path="/about/:lang?/" exact component={About}/>
Run Code Online (Sandbox Code Playgroud)

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

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

对于进一步的阅读