React Router动态路由配置报错及解决方案
动态配置Toolpad应用路由时空白页问题的解决
问题背景
开发基于Toolpad的带动态菜单的应用,配置动态路由后访问/TestStagionatura/Dashboard等路径时出现空白页,报错如下:
在路径"/TestStagionatura/Dashboard"匹配到的叶子路由没有element或Component,这会导致默认渲染一个值为null的
,最终出现空白页面。return (<Outlet />)
原始代码示例
configureRouters.js
const navigationItems = [ { title: "", icon:"",element:"Dashboard", path: '/TestStagionatura/Dashboard' }, { title: "", icon: "", element: "EntrataMerce", path: '/TestStagionatura/EntrataMerce' }, ] const getItemsMenu = () => { var children = [] navigationItems.map(async (item) => { children.push( { path: item.path, lazy: () => import(`../pages/${item.element}`), // 💤 Lazy load! }, ) }) return children; } const configureRouters = () => { var router1 = createBrowserRouter([ { Component: App, children: [ { path: '/', Component: Layout, }, { path: '/TestStagionatura', Component: Layout, children: getItemsMenu(), }, ], }, { path: '/TestStagionatura/auth', Component: AuthLayout, children: [ { path: 'login', element: <Login url={process.env.REACT_APP_API_URL_VALIDATE} application={process.env.REACT_APP_API_APP_CODE} />, } ], }, { path: '/TestStagionatura/NotAuthorized', element: <NotAuthorize description={'You do not have access for plant'} serviceName={'Seasoning Hams'} /> }, ]); return router1; }
app.js
return ( <AppProvider session={session} authentication={authentication} navigation={NAVIGATION} branding={BRANDING} > <Outlet /> </AppProvider> );
index.js
const router = configureRouters(); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <RouterProvider router={router} fallbackElement={<p>Loading...</p>} /> </Provider> );
layout.js
return ( <Box> {isAccess ? <DashboardLayout hideNavigation={false} slots={{ toolbarActions: Plant, sidebarFooter: SidebarFooter }}> <Outlet /> </DashboardLayout > ....... </Box> );
解决方案
1. 在Layout.js中添加Suspense包裹Outlet
修改Layout.js中的Outlet部分,用Suspense组件包裹,确保懒加载组件时有加载状态:
<Suspense fallback={renderLoader()}> <Outlet /> </Suspense>
2. 修正路由加载逻辑
修改getItemsMenu函数,将路由配置中的lazy字段替换为Component,并正确使用React.lazy包裹异步导入逻辑:
const getItemsMenu = () => { var children = [] navigationItems.map(item => { children.push( { path: item.path, Component: React.lazy(async () => await import(`../pages/${item.element}`)), }, ) }) return children; }
(注:需确保已导入React相关API,比如在文件顶部添加import React, { lazy, Suspense } from 'react';)
内容的提问来源于stack exchange,提问作者Marco Antonio Ferlito
相关产品推荐
相关产品推荐

