【问题标题】:how to handle multiple routes that match the same path如何处理匹配相同路径的多个路由
【发布时间】:2023-02-21 07:56:15
【问题描述】:
<Routes>
  <Route path="/cheese" element={<Home />} >
    <Route path="*" element={<Home />} />
  </Route>
  <Route path="/:category/:id" element={<Article />} />
</Routes>

在上面,如果url的路径是/cheese/12345,则匹配到第二个路由器,因此返回元素&lt;Article /&gt;

如何纠正这个?

我正在使用 React Router v6

【问题讨论】:

  • 这正是路由匹配的工作原理,您为什么期待其他一些行为?或者更确切地说,你到底想在这里发生什么?
  • 由于/cheese,我想要匹配第一条路线

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


【解决方案1】:

react-router-dom@6 路由总是与路径完全匹配,"/cheese/12345" 与非常通用的"/:category/:id" 路由路径完全匹配。

如果您希望第一个路由匹配 "/cheese" 以及任何“子路由”/后代路径,那么它应该在路径后附加一个通配符 "*" 匹配器。

例子:

<Routes>
  <Route path="/cheese/*" element={<Home />} />
  <Route path="/:category/:id" element={<Article />} />
</Routes>

【讨论】:

  • 我做了一个编辑。第一条路线实际上确实有一个带通配符的子路线
  • @BearBileFarmsisTorture 那不是子路线,那是嵌套路线,它们不是相当一样的东西。让我做一个测试和验证。
猜你喜欢
  • 2023-02-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多