React的異步組件

最近在學習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'));
複製代碼
相關文章
相關標籤/搜索