react異步加載組件


1. 創建 asyncComponent 異步加載工具

import React from 'react'

function asyncComponent(loadComponent){
    class AsyncComponent extends React.Component{
        static defaultProps = {
            loading: <p>Loading</p>,
            error: <p>Error</p>
        }
        constructor(props){
            super(props)
            this.loaad = this.load.bind(this)
            this.state = {
                module: null
            }
        }

        componentWillMount(){
            this.load(this.props)
        }
        load(props){
            this.setState({
                module: props.loading
            })
            loadComponent()
                .then( m=> {
                    let Module = m.default ? m.default: m
                    this.setState({
                        module: <Module {...props}/>
                    })
                }).catch((error)=>{
                    this.setState({
                        module: props.error
                    })
                    console.log(error)
                })
        }
        render(){
            return this.state.module
        }
    }
    
    return AsyncComponent
}

export default asyncComponent

2. 異步加載react組件

let Widget = asyncComponent(()=>import(`widgets/${type.charAt(0).toUpperCase()}${type.slice(1)}Chart`))
<Widget />

 

F12 查看資源network發現在異步組件mounted時瀏覽器會發送對應組件模塊的資源請求

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM