美文网首页
react异步加载组件

react异步加载组件

作者: _theFeng | 来源:发表于2019-04-11 09:46 被阅读0次
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'))

相关文章

网友评论

      本文标题:react异步加载组件

      本文链接:https://www.haomeiwen.com/subject/pauziqtx.html