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

React Router v5中如何避免重复编写路由URL?

React Router v5 优化嵌套路由URL,避免路径冗余

针对你遇到的重复编写父路由路径的问题,有三种实用方法可以简化代码:

1. 提取父路径为常量

把重复的父路由路径定义成常量,子路由通过模板字符串拼接,这样父路径需要修改时只改一处即可:

// 提取父路由路径为常量
const PARENT_IGD_PATH = '/admisi/rawat-darurat-igd';

const routes = [
  {
    path: PARENT_IGD_PATH,
    exact: true,
    sidebar: null,
    main: () => <> <RawatDaruratIGD/> </>
  },
  {
    path: `${PARENT_IGD_PATH}/registrasi-igd-umum`,
    sidebar: null,
    main: () => <> <h1>Ini Form</h1> </>
  }
];

2. 使用React Router嵌套路由特性

React Router v5支持嵌套路由,父路由组件内部可以渲染子路由,子路由的path只需写相对路径,无需重复父路径部分:

首先调整父路由配置(去掉exact,让子路由能匹配):

const routes = [
  {
    path: '/admisi/rawat-darurat-igd',
    sidebar: null,
    main: (props) => (
      <>
        <RawatDaruratIGD/>
        {/* 在父组件内渲染子路由 */}
        <Route
          path={`${props.match.path}/registrasi-igd-umum`}
          component={() => <> <h1>Ini Form</h1> </>}
        />
      </>
    )
  }
];

这种方式更符合路由的层级逻辑,也彻底避免了路径重复。

3. 层级化路由配置动态生成路径

如果路由数量较多,可以定义层级化的路由配置,通过遍历生成完整路径,适合复杂路由场景:

// 层级化路由配置
const rawRouteConfig = [
  {
    path: '/admisi/rawat-darurat-igd',
    exact: true,
    sidebar: null,
    main: () => <> <RawatDaruratIGD/> </>,
    children: [
      {
        path: 'registrasi-igd-umum',
        sidebar: null,
        main: () => <> <h1>Ini Form</h1> </>
      }
    ]
  }
];

// 递归生成完整路径的路由数组
const generateRoutes = (config, parentPath = '') => {
  let result = [];
  config.forEach(item => {
    const fullPath = parentPath ? `${parentPath}/${item.path}` : item.path;
    result.push({
      ...item,
      path: fullPath,
      // 移除children属性,避免干扰路由配置
      children: undefined
    });
    // 处理子路由
    if (item.children) {
      result = [...result, ...generateRoutes(item.children, fullPath)];
    }
  });
  return result;
};

// 生成最终可用的路由数组
const routes = generateRoutes(rawRouteConfig);

内容的提问来源于stack exchange,提问作者github.arief

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:01:28