手记

react异步加载组件,纯干货

    今天给大家分享一个react异步加载组件的方法:

import React, {Component} from "react";

import {Modal} from "antd";


const AsyncComponent = loadComponent => (

class AsyncComponent extends Component {

state = {

Component: null

}

componentDidMount() {

const me = this;

if(this.hasLodaedComponent()) return;

loadComponent()

.then(module => module.default)

.then(Component => {

me.setState({Component})

})

.catch(err => {

console.log(err);

Modal.info({

title: "系统提示",

content: "系统已更新,请刷新页面",

onOk: ()=>{

me.reloadSys()

}

})

})

}


hasLoadedComponent() this.state.Component !== null;

reloadSys = () => window.document.location.reload();


render(){

const Component = this.state.Component 

return Component ? <Component {...this.props}> : null

}

}

)


    使用

import AsyncComponent from "./AsyncComponent";


const User = AsyncComponent(

() => import(/* webpackChunckName: User */ "./User")

)


const R = () => {

<Switch>

<Route path="./user" component={User} />

</Switch>

}


0人推荐
随时随地看视频
慕课网APP