如何防止使用react-router v4匹配两条路由?

Whe*_*hee 7 react-router react-router-v4

我有以下两条路线:/items/items/buy.

每个路径对应于单个视图中的Tab.两条路线都使用精确的道具进行渲染,但仍然有两个标签在导航时被标记为活动/items/buy.

我已经尝试过使用withRouter,但我注意到要改变/items/items/sell解决问题,但我不想拥有这条路线.

我知道rrv4匹配我的路线的第一部分/items和其他路线/items/buy,但我认为如果我正在使用它不应该发生exact.有关为什么会发生这种情况的任何线索?

啊,我忘了说我已经在使用Switch了.

谢谢你的帮助!

小智 18

您需要将路线放在一个<Switch>组件中.该开关仅渲染匹配的第一条路线.

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>
Run Code Online (Sandbox Code Playgroud)


Whe*_*hee 0

问题是我用 LinkContainer 包装 NavItem,而 LinkContainer 没有精确的 prop。添加确切的道具解决了问题!