How to prevent matching two routes with react-router v4?

↘锁芯ラ 提交于 2019-12-08 18:07:42

问题


I have the following two routes: /items and /items/buy.

Each route corresponds to a Tab in a single view. Both routes are rendered with an exact prop, but still, two tabs are being marked as active when navigating to /items/buy.

I already tried using withRouter, but I noticed changing /items to /items/sell fixes the problem, but I don't wanna have that route.

I understand rrv4 is matching the first part of my route /items and the other route too /items/buy, but I think that shouldn't be happening if I'm using exact. Any clues on why this is happening?

Ahh I forgot to say I am already using a Switch.

Thanks for your help!


回答1:


You need to put your routes in a <Switch> component. The switch will only render the first route that matches.

import {Route, Switch} from 'react-router-dom';

<Switch>
  <Route exact path="/" component={Main} />
  <Route exact path="/items" component={SomeComponent} />
  <Route exact path="/items/buy" component={SomeOtherComponent} />
  <Route component={NotFound} />
</Switch>



回答2:


The problem was I was wrapping a NavItem with a LinkContainer and the LinkContainer did not have an exact prop. Adding the exact prop solved the issue!



来源:https://stackoverflow.com/questions/44958758/how-to-prevent-matching-two-routes-with-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!