react react-loadable異步組件(按需加載組件)

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,
    },

]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章