react 异步加载组件

30 阅读1分钟
function asyncComponent(loadComponent, type = 'async'){
    class AsyncComponent extends React.Component{
        static defaultProps = {
            loading: <p>Loading</p>,
            error: <p>Error</p>
        }
        constructor(props){
            super(props)
            this.load = this.load.bind(this)
            this.state = {
                module: null
            }
        }

        componentWillMount(){
            this.load(this.props)
        }
        load(props){
            this.setState({
                module: props.loading
            })
            Promise.resolve().then(() => {
                if (type === 'lazy') {
                    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)
                        })
                } else {
                    // 非import组件,只是单纯的异步加载
                    this.setState({
                        module: loadComponent
                    })
                }
            })
            // // 延时测试
            // setTimeout(() => {
            //     this.setState({
            //         module: loadComponent
            //     })
            // }, 1000)
        }
        render(){
            return this.state.module
        }
    }

    return AsyncComponent
}

export default asyncComponent