最近在學習react,用到了非同步元件,實現按需載入chunk.js,減輕首頁壓力。話不多說,直接上程式碼:
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;
}複製程式碼
在使用某個元件時:
import asyncComponent from './untils/asyncComponent';//非同步元件的位置
const Do = asyncComponent(() => import('./pages/Do'));
複製程式碼