乐趣区

关于前端:React-import按需异步加载asyncComponent

import()办法返回的是一个 Promise
asyncComponent 是一个返回组件的函数

const asyncComponent = (importComponent) => {
    return class extends Component {constructor(){super();
            this.state = {component: null}
        }
        componentDidMount() {importComponent().then(cmp => {
                this.setState({component: cmp.default});
            });
        }
        render() {
            const C = this.state.component;
            return C ? <C {...this.props} /> : null
        }
    }
}

应用:

const Home = AsyncCompoent(() => import('./Home/index/js'));
const City = AsyncCompoent(() => {impirt('./city/index.js')
});
退出移动版