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

React Router嵌套路由实现报错:Route需作为Routes子元素

React Router v6嵌套路由错误解决方法

错误原因

你遇到的报错是因为React Router v6强制要求所有<Route>组件必须直接作为<Routes>或另一个<Route>的children存在,不能直接在普通组件的JSX中渲染。你的代码里把嵌套子路由直接放到了<CustomRoute>的children中,导致<Route>被直接渲染,违反了v6的路由规则。

解决方案步骤

1. 调整路由渲染逻辑

修改renderRoutes函数,将子路由作为父<Route>的children属性,而非塞进element里:

import { Route, Routes } from 'react-router-dom';
import routes, { RouteModel } from './router/routes';
import CustomRoute from './router/CustomRoute';

const renderRoutes = (routes: RouteModel[]) => {
  return routes.map((route, index) => {
    const PageComponent = route.Page;
    return (
      <Route
        key={index}
        path={route.Path}
        element={
          <CustomRoute path={route.Path}>
            <PageComponent />
          </CustomRoute>
        }
      >
        {/* 子路由作为当前Route的children,而非element的内容 */}
        {route.SubItems?.length && renderRoutes(route.SubItems)}
      </Route>
    );
  });
};

const App = () => {
  return <Routes>{renderRoutes(routes)}</Routes>;
};

export default App;

2. 父页面添加Outlet组件

父路由对应的页面(比如ListCarPage)必须引入<Outlet>,用来渲染子路由的内容,否则子页面不会显示:

// page/car/list/page.tsx
import { Outlet } from 'react-router-dom';

const ListCarPage = () => {
  return (
    <div>
      <h1>车辆列表页</h1>
      {/* 子路由的内容会渲染到这个位置 */}
      <Outlet />
    </div>
  );
};

export default ListCarPage;

3. 优化路由配置(可选但推荐)

将子路由的路径改为相对路径,让路由结构更简洁清晰:

// router/routes.ts
const routes: RouteModel[] = [
  {
    Path: '*',
    Page: HomePage,
    Text: 'Home',
  },
  {
    Path: '/login',
    Page: LoginPage,
    Text: 'Login',
  },
  {
    Path: '/car',
    Page: ListCarPage,
    Text: 'Car',
    SubItems: [
      // 相对路径,等价于'/car/create'
      {
        Path: 'create',
        Text: 'Create',
        Page: CreateCarPage,
      },
    ],
  },
];

4. 确认CustomRoute组件逻辑

你的CustomRoute组件逻辑无需修改,它只负责包裹页面组件、处理权限跳转,符合当前需求:

// router/CustomRoute.tsx
import { Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import Layout from '../component/layout/Layout';

type Props = {
  children: React.ReactNode;
  path: string;
};

const CustomRoute = ({ children, path }: Props) => {
  const { authenticated } = useAuth();

  if (path === '/login') {
    return authenticated ? <Navigate to="/" /> : children;
  }

  return authenticated ? <Layout>{children}</Layout> : <Navigate to="/login" />;
};

export default CustomRoute;

关键规则提醒

  • React Router v6中,嵌套路由必须通过父Route的children定义,父页面通过<Outlet>承载子路由内容。
  • 所有<Route>必须被<Routes>或父<Route>包裹,不能作为普通组件直接渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:30:14