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

React-Router-Dom 6中如何为特定参数定义子路由?

React Router Dom 6 实现带步骤参数的向导路由布局

正确路由配置方案

方案1:父路由统一布局,子路由匹配步骤参数

这种写法最贴合需求:父路由负责渲染共用的WizardLayout,子路由通过:step参数匹配不同步骤,且子路由能直接通过useParams拿到参数。

import { useRoutes, Outlet, useParams } from 'react-router-dom';

// 共用布局组件,包含Outlet渲染子路由内容
const WizardLayout = () => {
  return (
    <div className="wizard-container">
      <header>向导流程共用顶部导航</header>
      <main>
        <Outlet /> {/* 步骤页面会渲染在这里 */}
      </main>
    </div>
  );
};

// 根据step参数渲染对应页面的组件
const StepRenderer = () => {
  const { step } = useParams();

  switch (step) {
    case 'step1':
      return <div>Step 1:填写基本信息</div>;
    case 'step2':
      return <div>Step 2:确认提交内容</div>;
    default:
      return <div>无效的步骤,请检查路径</div>;
  }
};

// 路由配置对象
const routes = [
  {
    path: '/wizard',
    element: <WizardLayout />,
    children: [
      {
        path: ':step', // 相对父路由的路径,最终匹配/wizard/:step
        element: <StepRenderer />
      }
    ]
  }
];

// 在根组件中使用useRoutes
function App() {
  return useRoutes(routes);
}

方案2:父路由直接包含step参数,用索引路由

如果想让父路由路径直接是/wizard/:step,需要用索引路由(index: true)避免路径冲突,此时step参数在父组件或子组件中都能通过useParams获取。

const routes = [
  {
    path: '/wizard/:step',
    element: <WizardLayout />,
    children: [
      {
        index: true, // 索引路由匹配父路由的完整路径
        element: <StepRenderer />
      }
    ]
  }
];

补充:固定步骤的单独路由配置

如果你的步骤是固定的(比如只有step1和step2),也可以直接给每个步骤写子路由,不用依赖参数:

const routes = [
  {
    path: '/wizard',
    element: <WizardLayout />,
    children: [
      { path: 'step1', element: <Step1Page /> },
      { path: 'step2', element: <Step2Page /> }
    ]
  }
];

踩坑说明

  • 你之前报错的原因是子路由写了绝对路径(比如/wizard/step1),React Router 6要求子路由路径必须是相对父路由的,绝对路径会触发“子路径必须以父级完整路径开头”的错误。
  • 当父路由路径带参数时,子路由用index: true就能自动继承父路由的参数,无需额外配置。

内容的提问来源于stack exchange,提问作者Ronny Efronny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:10:11