【问题标题】:React Router V4 allow only certain parameters in URLReact Router V4 仅允许 URL 中的某些参数
【发布时间】:2018-05-02 07:33:45
【问题描述】:

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

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

【问题讨论】:

标签: reactjs react-router react-router-v4


【解决方案1】:

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

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

<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

【讨论】:

  • 我是这样做的:&lt;Route exact path={/:lng?(en|de)} component={Page} /&gt; &lt;Route path={/:lng?(en|de)/someURL1} component={Page}/&gt; 但我有两个问题:不接受普通地址:www.website.com(/) 和lang 参数不知何故停止检测@ 987654327@。现在是undefined
  • 我可以得到this.props.match.params,你可以只发布代码吗?
  • index.js:` /:lng?(en|de)} component={Page} /> /:lng?(en|de)/url1} component={Page}/> /:lng?(en|de)/url2} component={Page}/> /:lng?(en|de)/url3} component={Page}/> ` 并且在 Page.jsthis.props.match.params.lngundefined 而没有 regex 表达式它会提取 lang来自 URL 的参数
  • 这样写/about/:lng(en|de)?
  • 很高兴我能帮上忙 :)
猜你喜欢
  • 2018-04-10
  • 2018-02-28
  • 1970-01-01
  • 2021-05-02
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多