问题
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