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

react-router-dom中createBrowserRouter懒加载箭头函数组件路由报错

React Router Lazy路由加载问题:箭头函数组件无法渲染的解决办法

问题原因

react-router-dom的createBrowserRouter中使用lazy选项时,默认会从导入的模块里查找名为Component的导出项。你的Contact组件默认导出的是名为Component的函数,刚好匹配这个规则;而About组件默认导出的是名为About的箭头函数,不符合预期,导致路由找不到组件,抛出Matched leaf route at location "/about" does not have an element or Component错误。

两种解决方法

方法1:手动指定组件映射

在lazy回调里,明确返回包含Component属性的对象,指向模块的默认导出:

{
  path: "about",
  lazy: () => import("./pages/About").then(module => ({ Component: module.default }))
}

方法2:统一组件导出名称

修改About组件的命名为Component,和Contact组件保持一致:

// pages/About.jsx
export const Component = () => {
  return <h1> About </h1>;
};

export default Component;

更通用的懒加载写法(推荐)

如果不想受限于Component这个特定名称,可以使用React原生的lazy和Suspense配合路由的element配置,这是更标准的懒加载方式:

import { lazy, Suspense } from 'react';
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import Layout from "./Layout";
import "./styles.css";

const About = lazy(() => import("./pages/About"));
const Contact = lazy(() => import("./pages/Contact"));

const routes = createBrowserRouter([
  {
    path: "/",
    element: (
      <Suspense fallback={<div>加载中...</div>}>
        <Layout />
      </Suspense>
    ),
    children: [
      { path: "about", element: <About /> },
      { path: "contact", element: <Contact /> }
    ]
  }
]);

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <RouterProvider router={routes} />
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:22:40