You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom中路径参数缺失时的重定向实现问题

react-router-dom中路径参数缺失时的重定向实现问题

我在react-router-dom中定义了如下路由:

<Route id='editor' path='editor' >
  <Route index element={<Editor />} />
  <Route id='edit' path='edit/:documentId' element={<Edit />} />
</Route>

这样设置后,我可以访问以下路径:

  • "/editor" <---- 会渲染 <Editor /> 组件
  • "/editor/edit/13" <---- 会渲染 <Edit /> 组件,并加载documentId为13的文档

不过,当我在地址栏输入路径"/editor/edit"(注意此时缺失documentId参数)时,我希望能重定向到"/editor"。

注意:我试过把documentId设为可选参数(在documentId后加问号):

<Route id='edit' path='edit/:documentId?' element={<Edit />} />

但这样会渲染<Edit />组件,只是documentId的值为undefined,这并不是我想要的效果。我想要的是重定向到"/editor"并渲染<Editor />组件。

我该怎么实现这个需求呢?

备注:内容来源于stack exchange,提问作者Greeso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:09:35