react react-loadable异步组件(按需加载组件)

龙令
2023-12-01
1、引入
	cnpm install --save react-loadable
	
2、使用

	import React from 'react';
	import Loadable from 'react-loadable';
	
	const LoadableComponent = Loadable({
	  loader: () => import('需要加载的异步组件路径'),
	  loading(){
	      return 加载过程中显示的内容
	  },
	});
	
	export default ()=><LoadableComponent />
	
3、将原本路由组件替换成改异步组件
	将原本导入的组件换成该组件即可
	
4、若原本路由组件使用了路由的属性(props.history等)
	在换成异步组件的时候,本身要使用withRouter导入路由组件的属性
	因为现在的路由组件是异步组件

代码示例:
异步组件集合:

import {Loading} from '../components'
import Loadable from 'react-loadable'


const Dashboard=Loadable({
    loader:()=>import('./Dashboard'),
    loading:Loading
})
const Login=Loadable({
    loader:()=>import('./Login'),
    loading:Loading
})

const NotFound=Loadable({
    loader:()=>import('./NotFound'),
    loading:Loading
})

const Settings=Loadable({
    loader:()=>import('./Settings'),
    loading:Loading
})

const ArticleList=Loadable({
    loader:()=>import('./Article'),
    loading:Loading
})

const ArticleEdit=Loadable({
    loader:()=>import('./Article/Edit'),
    loading:Loading
})



export {
    Dashboard,
    Login,
    NotFound,
    Settings,
    ArticleEdit,
    ArticleList
}

路由文件中使用异步组件:

import {
    Dashboard,
    Login,
    NotFound,
    Settings,
    ArticleEdit,
    ArticleList
} from '../views'

export const mainRouter=[
    {
        pathname:'/login',
        component:Login,
    },
    {
        pathname:'/404',
        component:NotFound,
    }
]

export const adminRouter=[
    {
        pathname:'/admin/dashboard',
        component:Dashboard,
    },
    {
        pathname:'/admin/settings',
        component:Settings,
    },
    {
        pathname:'/admin/article',
        component:ArticleList,
        exact:true
    },
    {
        pathname:'/admin/article/edit/:id',
        component:ArticleEdit,
    },

]
 类似资料: