继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

react异步加载组件,纯干货

幕布斯7119047
关注TA
已关注
手记 432
粉丝 28
获赞 102

    今天给大家分享一个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>

}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP