实现react路由动态加载的组件

时间:2021-10-12 11:40:44
import React, { Component } from 'react';
import Loading from '../../base/nc_Loading';
/*
* date: 2018/06/28
* asyn load components
* useage: const newcom = asyncComponent(() => import(/ * webpackChunkName: "chunkname" * / 'pages/so/edit'));
*/
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null,
};
}
componentDidMount() {
this.asyncGetComponent();
}
asyncGetComponent = () => {
const self = this;
new Promise((resolve) => {
const asyncCom = importComponent();
resolve(asyncCom);
}).then((asyncCom) => {
const { default: component } = asyncCom;
self.setState({
component,
});
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : <Loading text="正在加载中..." />;
}
}
return AsyncComponent;
}