首先新建文件Bundle.js。
// Bundle.js
import React from 'react';
export default class Bundle extends React.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對(duì)象; mod.default導(dǎo)出默認(rèn)
props.load().then((mod) => {
this.setState({
mod: mod.default ? mod.default : mod
});
});
}
render() {
return this.state.mod ? this.props.children(this.state.mod) : null;
}
}
然后如下使用即可。

11.png
效果:
剛開(kāi)始在 / 路由,加載到的文件有

22.png
然后到 /todo-app 路由,加載的文件有

33.png
紅色框中的 0.chunk.js 就是到 /todo-app 路由,按需加載到的文件。