const asyncComponent = loadComponent => (
class AsyncComponent extends React.Component {
constructor(props){
super(props)
this.state={
Component: null,
}
}
componentWillMount() { // eslint-disable-line
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;
}
}
);
实用方法
asyncComponent(()=>import('./pages/Area'))