import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { lazy, Suspense } from 'react';
// 定义路由数组
const routes = [
{
path: '/',
exact: true,
component: lazy(() => import('./pages/Home')),
},
{
path: '/about',
component: lazy(() => import('./pages/About')),
routes: [
{
path: '/about/me',
component: lazy(() => import('./pages/About/Me')),
},
{
path: '/about/company',
component: lazy(() => import('./pages/About/Company')),
},
],
},
{
path: '/contact',
component: lazy(() => import('./pages/Contact')),
},
{
path: '*',
component: lazy(() => import('./pages/NotFound')),
},
];
// 递归生成路由组件
const renderRoutes = (routes) => (
<Switch>
{routes.map((route, i) => {
const { path, exact, component: Component, routes: subRoutes } = route;
return (
<Route
key={i}
path={path}
exact={exact}
render={(props) => (
<Component {...props}>
{subRoutes && renderRoutes(subRoutes)}
</Component>
)}
/>
);
})}
</Switch>
);
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
{renderRoutes(routes)}
</Suspense>
</Router>
);
}
export default App;
在这个示例代码中,我们首先定义了一个路由数组,每个路由对象包括路由路径(path)、是否精确匹配(exact)、对应的组件(component)和子路由数组(routes)。
然后,我们使用递归方式遍历路由数组,生成对应的路由组件。每个路由组件通过懒加载方式加载对应的组件,如果该路由还有子路由,则递归生成子路由组件。最终,将生成的路由组件包裹在
在App组件中,我们使用组件包裹生成的路由组件,并传入fallback属性,指定加载懒加载组件时的加载占位符。
这样,我们就可以将所有路由定义在一个数组中,通过递归方式生成对应的路由组件,使用懒加载和嵌套子路由的方式实现一个完整的路由系统。