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

嵌套路由中从索引路由跳转至父路由的路径配置问题

React嵌套路由跳转父路由路径重复问题解决

问题场景

在React嵌套路由结构中,需要从profile/:userId的索引路由(对应<ProfileInfo />组件)跳转至其父路由profile/:userId。当前使用<MenuItem link={./profile/${userId}}>Profile info</MenuItem>时,跳转后路径变为http://localhost:3000/profile/62e96087d8d815f327dc5125/profile/62e96087d8d815f327dc5125,出现路径重复,期望路径为http://localhost:3000/profile/62e96087d8d815f327dc5125。

现有路由结构:

<Routes>
  <Route path={pageRoutes.HOME} element={<LayoutPage />}>
    <Route index element={<HomePage />} />
    <Route element={<ProtectedPage />}>
      <Route path={pageRoutes.PROFILE} element={<LayoutProfilePage />}>
        <Route index element={<ProfileInfo />} />
        <Route path={pageRoutes.EDIT_PANEL} element={<EditProfilePanel />} />
        <Route path={pageRoutes.ADMIN_PANEL} element={<AdminPanel />} />
        <Route path={pageRoutes.CART} element={<CartPage />} />
      </Route>
      <Route path={pageRoutes.PRODUCT} element={<ProductPage />} />
      <Route path={pageRoutes.ADMIN} element={<AdminPage />} />
    </Route>
    <Route path={pageRoutes.ABOUT} element={<AboutPage />} />
  </Route>
  <Route path={pageRoutes.NOT_FOUND} element={<NotFoundPage />} />
</Routes>

路由枚举定义:

enum pageRoutes {
  HOME = "/",
  PROFILE = "profile/:userId",
  EDIT_PANEL = "editPanel",
  ADMIN_PANEL = "adminPanel",
  CART = "cart",
  PRODUCT = "product",
  ABOUT = "about",
  ADMIN = "admin",
  NOT_FOUND = "*",
}

原因分析

使用相对路径./profile/${userId}时,路径解析会基于当前页面的URL进行追加。当处于profile/:userId的索引路由页面时,当前URL为/profile/xxx,此时相对路径会在该基础上追加profile/xxx,最终形成重复路径。

解决方案

方案1:使用绝对路径

直接从根路径构建目标URL,避免相对路径的叠加问题:

<MenuItem link={`/profile/${userId}`}>Profile info</MenuItem>

也可以利用路由枚举替换参数,提升可维护性:

<MenuItem link={`/${pageRoutes.PROFILE.replace(':userId', userId)}`}>Profile info</MenuItem>

方案2:使用相对路径指向当前路由

由于索引路由的路径本身就是父路由profile/:userId的路径,直接使用./即可指向当前父路由路径:

<MenuItem link="./">Profile info</MenuItem>

这种方式同时适用于从editPanel等子路由跳转回父路由的场景。

方案3:编程式导航

如果是函数组件,可使用useNavigate钩子实现编程式跳转,灵活性更高:

import { useNavigate } from 'react-router-dom';

const ProfileMenu = ({ userId }) => {
  const navigate = useNavigate();

  const goToProfile = () => {
    navigate(`/profile/${userId}`);
  };

  return <MenuItem onClick={goToProfile}>Profile info</MenuItem>;
};

内容的提问来源于stack exchange,提问作者Radomir Radionov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:09:13