React 路由器子路由将其重定向到带有参数的错误网址

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

如果使用react-router v6缺少正确的路径,我正在尝试创建重定向路径

这是我的路线

<Route path='/recipe/:id' element={<RecipePage />}>
        <Route index element={<Navigate to='/recipe/:id/ingredients' replace />}/>
        <Route path='/recipe/:id/ingredients' element={<Ingredients />} />
        <Route path='/recipe/:id/instructions' element={<Instructions />} />
      </Route>

如果网址中缺少单词

ingredients
instructions
,我想重定向到正确的路径。

当网址为

http://localhost:5173/recipe/5431/
时的示例,我想将其重定向到
http://localhost:5173/recipe/5431/ingredients

但是上面的代码不断重定向我

http://localhost:5173/recipe/:id/ingredients
而不是
http://localhost:5173/recipe/5431/ingredients

我的代码有什么问题?

reactjs react-router-dom
1个回答
0
投票

您不需要嵌套路由中的完整路径。考虑以下几点:

<Route path='/recipe/:id' element={<RecipePage />}>
  <Route index element={<Navigate to='ingredients' replace />}/>
  <Route path='ingredients' element={<Ingredients />} />
  <Route path='instructions' element={<Instructions />} />
</Route>
© www.soinside.com 2019 - 2024. All rights reserved.