我有一个名为routes.js的文件
import Country from '../src/components/country/Country';
import Countries from '../src/components/country/CountriesList';
export const routes = [
{
name: 'COUNTRY',
children: [
{
name: 'Create',
path: '/country',
component: Country,
},
{
name: 'Update',
path: '/update-country',
component: Country,
isHidden: true,
},
{
name: 'View',
path: '/countries',
component: Countries,
},
],
},
]
在我的app.js中,我导入路由并执行如下操作
<Switch>
<Route path="/" exact component={Login}></Route>
<Route path="/permission-denied" exact component={PermissionDenied}></Route>
{routes
.flatMap((items) => items.children)
.map(({ component, path }) => (
<ProtectedRoute component={component} exact path={path} />
))}
<Route component={NotFound}></Route>
</Switch>;
这是没有错误的工作!但是我想拆分我的代码,以减少我的包大小。如何在routes.js文件中执行此操作?
发布于 2020-11-18 00:06:52
使用react.lazy非常简单:
import { lazy } from 'react';
// just change these lines
const Country = lazy(() => import('../src/components/country/Country'));
const Countries = lazy(() => import('../src/components/country/CountriesList'));
export const routes = [
{
name: 'COUNTRY',
children: [
{
name: 'Create',
path: '/country',
component: Country,
},
{
name: 'Update',
path: '/update-country',
component: Country,
isHidden: true,
},
{
name: 'View',
path: '/countries',
component: Countries,
},
],
},
]注意:请确保在渲染这些组件的树上方的某个位置有一个带有fallback属性的Suspense组件。
如下所示:
import React, { Suspense } from 'react';
<Suspense fallback={<></>}>
<Switch>
<Route path="/" exact component={Login}></Route>
<Route path="/permission-denied" exact component={PermissionDenied}></Route>
{routes
.flatMap((items) => items.children)
.map(({ component, path }) => (
<ProtectedRoute component={component} exact path={path} />
))}
<Route component={NotFound}></Route>
</Switch>
</Suspense>https://stackoverflow.com/questions/64878588
复制相似问题