美文网首页
react异步加载组件

react异步加载组件

作者: Issho | 来源:发表于2019-09-30 10:35 被阅读0次

☼ 注:笔者的文章是根据自己当前项目做的笔记,具体应用请参照自己实际项目情况

1、在根目录新建一个asyncLoad.jsx文件

import React, { Component } from 'react'
import { Icon } from 'antd'

export default load => (
    class ContentComponent extends Component {
        state = {
            com: null
        }

        componentDidMount() {
            load().then(mod => {
                return this.setState({ com: mod.default || mod })
            })
        }

        render() {
            if (this.state.com) {
                return (<this.state.com {...this.props} />)
            }
            return <Icon type="loading" />
        }
    }
)

2、在引入组件的时候使用

import React, { Component } from 'react'
import { Route, Switch } from 'react-router-dom'
import asyncLoad from '@/asyncLoad'

const CommunityView = asyncLoad(() => import('./component/community-view'))

class Community extends Component {
  render(
    <Switch>
       <Route exact path='/community/communityView ' component={CommunityView } />
    </Switch>
  )
}

相关文章

网友评论

      本文标题:react异步加载组件

      本文链接:https://www.haomeiwen.com/subject/oyesyctx.html