React 项目通过create-react-app 命令创建,版本为2.0.3.
import React from \\\\\\\'react\\\\\\\'
const AsyncComponent = loadComponent => (
class AsyncComponent extends React.Component {
state = {
Component: null,
}
componentWillMount() {
if (this.hasLoadedComponent()) {
return;
}
loadComponent()
.then(module => module.default)
.then((Component) => {
this.setState({Component});
})
.catch((err) => {
console.error(`Cannot load component in <AsyncComponent />`);
throw err;
});
}
hasLoadedComponent() {
return this.state.Component !== null;
}
render() {
const {Component} = this.state;
return (Component) ? <Component {...this.props} /> : null;
}
}
);
export default AsyncComponent;
import React from \\\"react\\\";
import {
Route
} from \\\'react-router-dom\\\'
import asyncComponent from \\\'./asyncComponent\\\'
//import Map from \\\"../pages/Map\\\";
const MapTest = asyncComponent(
() => import(/* webpackChunkName: \\\"map_test\\\" */\\\'../pages/Map\\\')
)
export default (
<Route key=\\\"map\\\" path=\\\'/map\\\' component={MapTest} />
);
配置完成后从其他模块切换到map会发现请求了 map_test.trunk.js