最近在学习react,用到了异步组件,实现按需加载chunk.js,减轻首页压力。话很少说,直接上代码:react
import React, { Component } from "react";
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = { component: null }; }
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({component});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
} }
return AsyncComponent;
}复制代码
在使用某个组件时:bash
import asyncComponent from './untils/asyncComponent';//异步组件的位置
const Do = asyncComponent(() => import('./pages/Do'));
复制代码