【问题标题】:React Router 4 and exact path with dynamic paramReact Router 4 和带有动态参数的确切路径
【发布时间】:2019-07-25 22:49:36
【问题描述】:

我在每条路径上都显示组件时遇到问题,因为 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 组件仍在渲染中。我猜问题出在路径上,因为它需要参数:username,并且紧随/(root)之后。难道我做错了什么?我可以为/:username 添加另一条路线,例如/profile/:username,但如果可能的话,我想保持原样。

【问题讨论】:

  • 这 3 个是否在同一个 Switch 语句中?

标签: reactjs react-router react-router-v4 react-router-dom


【解决方案1】:

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

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:username" render={props => <Profile {...props} />} />
  <Route path="/" component={Explore} />
  <Route component={NotFoundPage} />
</Switch>

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2019-07-02
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多