React router v6:如何忽略起始路径并评估其余路径

React router v6: How to ignore beginning path and evaluate the rest of it

我正在尝试在浏览器转到任何以 /product/:productId 结尾的 url 时呈现组件 ProductDetail,例如 http://localhost:3000/collection/323/product/526311418

我目前拥有的:

import { Routes, Route } from 'react-router-dom';

const App = () => {
    return (
        <Routes>
            <Route path='/' element={<Navigation />}>
                <Route index element={<Home />} />
                <Route path='collection/:collectionId' element={<Collection />} />
                <Route path=':AnyValue*/product/:productId' element={<ProductDetail />} />
            </Route>
        </Routes>
    );
}

react-router-dom@6 不使用 RegExp 进行任何路径处理。您需要明确定义要匹配的路由。

示例:

<Routes>
  <Route path="/" element={<Navigation />}>
    <Route index element={<Home />} />
    <Route path="collection/:collectionId" element={<Collection />}> // *
      // matches "/collection/323/product/526311418"
      <Route path="product/:productId" element={<ProductDetail />} />
    </Route>
    // matches "product/526311418"
    <Route path="product/:productId" element={<ProductDetail />} />
  </Route>
</Routes>

* 注意: 为此 Collection 还需要为嵌套路由呈现 Outlet