react异步加载组件,纯干货

2022/6/14 4:20:06

本文主要是介绍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>

}




这篇关于react异步加载组件,纯干货的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程