React Router v6 中的延迟加载路由

问题描述 投票:0回答:3

我正在尝试使用 React Router v6 中的

createBrowserRouter
函数延迟加载路由元素,但我不断收到此错误:`位置“/admin/reports/enrollees”处的匹配叶路由没有元素或组件。这意味着默认情况下它将呈现空值,从而导致“空”页面。 这是我的路线文件:

export default createBrowserRouter([
    {
        path: '/admin/reports',
        children: [
            {
                path: '',
                element: <Index />,
            },
            {
                path: 'enrollees',
                lazy: () => import('../../components/Reports/Enrollees'),
            },
            {
                path: 'facilities',
                lazy: () => import('../../components/Reports/Facilities'),
            }
        ],
    }
])

我一开始尝试这样做:

export default createBrowserRouter([
    {
        path: '/admin/reports',
        children: [
            {
                path: '',
                element: <Index />,
            },
            {
                path: 'enrollees',
                element: lazy(() => import('../../components/Reports/Enrollees')),
            },
            {
                path: 'facilities',
                element: lazy(() => import('../../components/Reports/Facilities')),
            }
        ],
    }
])

但是我收到错误:

Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

reactjs react-router react-router-dom async-components
3个回答
15
投票

我也遇到了同样的问题,我是这样解决的

{
  path: "dashboard",
  lazy: async () => {let { Dashboard } = await import("./pages/Dashboard")
    return { Component: Dashboard }},  
}

6
投票

这个奇怪的问题困扰了我几个小时,但我终于弄清楚了问题所在

首先确保您的组件名称是

Component
,然后使用命名导出而不是默认导出

例如。 YourComponent.jsx

export function Component(){
  return <div>something</div>
}

路线对象

{
  path: 'your-component',
  lazy: () => import('./YourComponent'),
}

如果您想保留组件名称并使用默认导出,您可以这样做

例如。 YourComponent.jsx

export default function YourComponent(){
  return <div>something</div>
}

路线对象

{
  path: 'your-component',
  async lazy() {
    let YourComponent = await import("./YourComponent");
    return { Component: YourComponent.default };
  },
}

0
投票

这是一个可重用的实用函数,可以使延迟加载路线更清晰:

export const lazyRoute = <T = any>(
  importFn: () => Promise<T>,
  componentName: keyof T
) => async () => {
  const module = await importFn();
  return { Component: module[componentName] };
};

// Usage
const router = createBrowserRouter([
  {
    path: "/admin/reports/enrollees",
    lazy: lazyRoute(() => import("./pages/Reports"), 'ReportsPage'),
  }
]);
© www.soinside.com 2019 - 2024. All rights reserved.