简体   繁体   English

React Router V4阻止匹配子路由

[英]React router v4 prevent matching child routes

I encountered a problem with React Router v4 Switch component. 我遇到了React Router v4交换机组件的问题。 I'm quite surprised that i couldn't find a relevant thread for this problem. 我为这个问题找不到相关的线索感到非常惊讶。 A common Switch will look like this: 常见的Switch如下所示:

<Switch>
  <Route path='/path1' component={Path1Component}/>
  <Route path='/path2' component={Path2Component}/>
  <Route exact path='/' component={Home}/>
  <Route component={NotFound}/>
</Switch>

This means that when i'm on a path: '/' i get a Home component, on '/path1' i get a Path1Component and on path '/foobar' i get a NotFound component. 这意味着当我在路径上时:'/'我得到一个Home组件,在'/ path1'我得到一个Path1Component,而在路径'/ foobar'我得到一个NotFound组件。 And that is perfectly fine 那很好

However when i'm on '/path1/foobar' route i also get the Path1Component. 但是,当我在“ / path1 / foobar”路线上时,我也会得到Path1Component。 This behaviour is not correct in every case - this time i do not want any nested routes for '/path1' route. 此行为在每种情况下都不正确-这次我不希望'/ path1'路由有任何嵌套路由。 '/path1/foobar' should get a NotFound component, any string, with '/' or without after '/path1' should return NotFound component. '/ path1 / foobar'应该得到一个NotFound组件,任何带'/'或不带'/ path1'之后的字符串都应该返回NotFound组件。

What would be the preferred resolution to this problem? 解决此问题的首选解决方案是什么? I could just add exact to every path, but wouldn't that be overbloating the code? 我可以在每条路径上都添加精确的代码,但这不会使代码过于夸张吗? I feel like that should be the default, but it's not the case. 我觉得这应该是默认设置,但事实并非如此。

Even on React Router v4 docs, like here . 即使在React Router v4文档上,例如here I see this problem - here '/will-match/foo' will also match. 我看到了这个问题-这里的'/ will-match / foo'也将匹配。 What are your thoughts? 你怎么看?

There is a discussion here , but to make it short : it would break existing code . 有一个讨论, 在这里 ,但要长话短说: 它会破坏现有的代码 If this were to change, you'd have to do exact={false} if you want to match child routes without doing 'path1/child1'. 如果要更改此设置,则要匹配子路由而不执行“ path1 / child1”,则必须执行exact={false}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM