在单页应用中,路由按需加载是十分有必要的,如果一次性加载全部js的话,随着应用的功能丰富,js文件也必将增大,那么第一次下载的时候必将变慢,影响用户体验。本文分享react-routerV4版本的按需加载。
异步加载包装组件
首先我们需要一个异步加载包装组件
import { Component } from 'react'
export default class Bundle extends Component {
constructor(props) {
super(props);
this.state = {
mod: null
};
}
componentWillMount() {
this.load(this.props)
}
componentWillReceiveProps(nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps)
}
}
load(props) {
this.setState({
mod: null
});
//注意这里,使用Promise对象; mod.default导出默认
props.load().then((mod) => {
this.setState({
mod: mod.default ? mod.default : mod
});
});
}
render() {
return this.state.mod ? this.props.children(this.state.mod) : null;
}
}
路由配置
import React from 'react'
import {
Route
} from 'react-router-dom'
import App from '../App'
import Bundle from '../components/Bundle'
const Find = (props) => (
<Bundle load={() => import('../components/Find')}>
{(Find) => <Find {...props}/>}
</Bundle>
);
const Home = (props) => (
<Bundle load={() => import('../containers/Home')}>
{(Home) => <Home {...props}/>}
</Bundle>
);
const routes = (
<Route>
<div>
<Route path="/" component={App} />
<Route path="/home" component={Home} />
<Route path="/find" component={Find} />
</div>
</Route>
)
export default routes;
按照如上配置,webpack打包时就可以实现路由的按需加载了。