React Router 4 和带有动态参数的精确路径

2024-03-11

我在每个路径上显示组件时遇到问题,因为 React Router 4 没有对该路径使用精确的(或者看起来如此)。

<Route path="/" exact component={Explore} />
<Route path="/about" component={About} />

// The one making problems
<Route
    path="/:username"
    exact={true}
    render={props => <Profile {...props} />}
/>

所以当我去http://example.com/about http://example.com/about,我的 Profile 组件仍在渲染中。我猜问题出在路线中,因为它期望参数:username接下来就是/(根)。难道我做错了什么?我可以添加另一条路线/:username, like /profile/:username,但如果可能的话,我想保持原样。


假设您没有使用 Switch。 Switch 将解决您的问题,因为它只会渲染第一个匹配的路径。

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:username" render={props => <Profile {...props} />} />
  <Route path="/" component={Explore} />
  <Route component={NotFoundPage} />
</Switch>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Router 4 和带有动态参数的精确路径 的相关文章

随机推荐