【问题标题】:Route with /:userId interrupt other path带有 /:userId 的路由中断其他路径
【发布时间】:2020-09-04 11:04:07
【问题描述】:

我的路线有问题。

我有这个代码:

<Switch>
 <Route path="/Register" component={Register} />
 <Route path="/:userId" component={UserProfile} />
 <Route path="/direct/inbox" component={Messenger} />

在组件(UserProfile)中,我使用 useParams 来捕获 userId,但我的问题是当我尝试转到 /direct/inbox 时,它呈现 UserProfile 的组件(当然给我错误)。

所以我的问题是,如何在使用 :userId 时渲染其他路径???

***顺便说一句,寄存器的路径没有任何问题,它工作正常。

【问题讨论】:

  • 我认为您必须将:userId 路由放在/direct/inbox 路由之后的底部
  • 这也行得通.. 不知道,谢谢

标签: reactjs react-router-dom


【解决方案1】:

没关系,我解决它... 我在 userId 路径中添加了“精确”。 如果有人有其他解决方案,我不介意尝试。

<Switch>
<Route path="/Register" component={Register} />
<Route exact path="/:userId" component={UserProfile} />
<Route path="/direct/inbox" component={Messenger} />

【讨论】:

    【解决方案2】:

    使用exact 不会解决问题,因为如果路径是/direct/inbox,那么它将匹配exact path="/:userId"。所以我们能做的就是让&lt;Route path="/:userId" component={UserProfile} /&gt;成为最后一条路线。因此,当/direct/inbox 匹配路径时,它将与预期的路由匹配,并呈现相应的组件。

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2023-03-30
      • 1970-01-01
      • 2017-03-22
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2021-04-04
      相关资源
      最近更新 更多