使用动态参数反应路由器4和精确路径

问题描述 投票:2回答:1

我在每个路径上显示组件的问题,因为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时,我的Profile组件仍在渲染中。我猜问题是在路线上,因为它期望param :username,并且在/(root)之后。难道我做错了什么?我可以为/:username添加另一条路线,比如/profile/:username,但我想保持原样,如果有可能的话。

reactjs react-router react-router-v4 react-router-dom
1个回答
6
投票

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

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:username" render={props => <Profile {...props} />} />
  <Route path="/" component={Explore} />
  <Route component={NotFoundPage} />
</Switch>
© www.soinside.com 2019 - 2024. All rights reserved.