为什么带有2个可选参数的React Route与简单URL不匹配

时间:2019-05-03 06:50:19

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

仅供参考,我正在使用React Router 5。 我的package.json中具有以下依赖项:

  

“ react-router-dom”:“ ^ 5.0.0”,

[问题以更简化的示例进行编辑]

让我描述一下我面临的问题。以下所有网址

http://localhost:3001/contact
http://localhost:3001/contact/
http://localhost:3001/contact/john50

符合以下路线(带有1个可选参数)

<Route path="/contact/:name([A-Za-z]+)?" component={Contact} />

JSfiddle for above behaviour.

然后,我通过添加另一个可选参数age来更新了上述Route。 看起来像这样:

<Route path="/contact/:name([A-Za-z]+)?:age(\d{2})?" component={Contact} />

为什么此具有2个可选参数的新路由与此URL匹配:

http://localhost:3001/contact/

,而不是通过此URL:

http://localhost:3001/contact

Jsfiddle for this weird behaviour

为什么?有人可以解释吗?

2 个答案:

答案 0 :(得分:0)

您必须将参数与/一起包装在可选正则表达式中,方法是将其包装在()

<Route path="/about/:param1(\d{2}-\d{2}-\d{4})?/:param2(\.[A-Za-z]+)?" component={About} />

注意:参数需要与/分开,而您没有。您可以将路线设置为

<Route path="/about/:param1(\d{2}-\d{2}-\d{4})?/:param2(\.[A-Za-z]+)?" component={About} />

,然后您的导航链接将

const Navigation = () => (
    <ul className="navLinks">
      <li><NavLink  to="/">Home</NavLink></li>
      <li><NavLink to="/contact/john/50">Working Contact</NavLink></li>
      <li><NavLink to="/contact/">Contact With Slash</NavLink></li>
    <li><NavLink to="/contact">Contact Without Slash</NavLink></li>
    </ul>
);

工作演示

答案 1 :(得分:0)

尝试一下

<Route path="/contact/:name?/:age?" component={Contact} />

另请参见thisthis