1. 安装
- 功能: 实现路由中组件的按需加载,提高首屏页面加载效率。
yarn add react-loadable
2. 封装公用组件(loadable.js)
import React from 'react'
import Loadable from 'react-loadable'
//通用的过场组件
const loadingComponent = () => {
return (
<div>loading...</div>
)
}
//过场组件默认采用通用的,若传入了loading,则采用传入的过场组件
export default (loader, loading = loadingComponent) => {
return Loadable({
loader,
loading
})
}
3. 引入到具体的使用中(加载要展示的组件)
import Loadable from './components/loadable';
const Home = Loadable(() => import('./components/Home/Home'));
const Routes = () => (
<Router>
<ul>
<li><Link to='/home'>home</Link></li>
<li><Link to='/about'>about</Link></li>
</ul>
<Switch>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>