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

React 18报错:[MainLayoutRoute]非<Route>组件问题求助

React 18 + React Router v6 适配:修复自定义布局路由报错问题

升级到React 18后,原React Router v5的自定义布局路由写法会因为API变更抛出[MainLayoutRoute] is not a <Route> component错误,核心原因是:

  • React Router v6要求<Routes>的直接子组件必须是<Route>或<React.Fragment>,自定义组件不能直接嵌套
  • <Route>不再支持component和render属性,统一使用element传递组件

修复后的代码实现

import { Navigate, Route, useLocation } from 'react-router-dom';

const MainLayoutRoute = ({ path, element, ...rest }) => {
  const ProtectedLayout = () => {
    const location = useLocation();
    
    // 未登录时重定向到登录页
    if (!auth.BasicAuth()) {
      return (
        <Navigate
          to={{
            pathname: "/login",
            state: { from: location },
          }}
          replace
        />
      );
    }

    // 已登录时渲染导航栏+目标页面
    return (
      <>
        <Navbar />
        {element}
      </>
    );
  };

  return <Route path={path} {...rest} element={<ProtectedLayout />} />;
};

使用方式

在路由配置中直接使用MainLayoutRoute,和标准<Route>用法一致:

<Routes>
  <MainLayoutRoute path="/dashboard" element={<Dashboard />} />
  <MainLayoutRoute path="/profile" element={<UserProfile />} />
  <Route path="/login" element={<LoginPage />} />
</Routes>

关键变更点

  1. 替换Redirect为Navigate:React Router v6移除了Redirect组件,改用Navigate,通过replace属性控制跳转是否替换历史记录
  2. 改用useLocation钩子:v6不再通过props传递location,需用useLocation获取当前路由位置
  3. 统一使用element属性:原component/render属性被废弃,所有路由内容通过element传递
  4. 返回标准<Route>组件:让自定义路由组件返回合法的<Route>,满足<Routes>的子组件要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:30:58