react 封装异步加载路由公共组件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45115705/article/details/101321527

封装异步加载路由组件
asyncComponent.jsx

import React from 'react';
/**
 * 异步加载组件
 * @param {*} importComponent 
*/

export default function asyncComponent(importComponent) {
    class AsyncComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                component: null
            }
        }
        async componentDidMount() {
           let { default: component} = await importComponent()
           this.setState({ component })
        }
        render() {
          const C = this.state.component;
          return C? <C { ...this.props } />: null
        }
    }
    return AsyncComponent
}

项目路由配置文件,直接使用即可
router/index.js

	const Layout = asyncComponent(() => import("../components/layout/index"))

PS:未来的你,一定会感谢今天拼命努力的自己!

猜你喜欢

转载自blog.csdn.net/weixin_45115705/article/details/101321527