#react懒加载引入组件

  1. 需要一个懒加载函数:asyncComponent.js
import React, { Component } from "react";

export default function asyncComponent(importComponent) {
    class AsyncComponent extends Component {
        constructor(props) {
            super(props);

            this.state = {
                component: null
            };
        }

        async componentDidMount() {
            const { default: component } = await importComponent();

            this.setState({
                component: component
            });
        }

        render() {
            const C = this.state.component;

            return C ?  : null;
        }
    }

    return AsyncComponent;
}

因为使用了async await,所以需要引入:

npm install babel-polyfill --save

并且在index.jsx中引用:
import 'babel-polyfill'
  1. route.jsx文件中进行懒加载设置:
import React, { Component } from 'react'
import asyncComponent from './js/asyncComponent.js'
import {Route, HashRouter} from 'react-router-dom'
// import Index from './components/Index'
// import Basic from './components/video/Basic'
// import FaceIndex from './components/face/Index'
// import VideoIndex from './components/video/Index'
// import VideoDetail from './components/video/Video'
const Index = asyncComponent(() => import('./components/Index'));
const Basic = asyncComponent(() => import('./components/video/Basic'));
const FaceIndex = asyncComponent(() => import('./components/face/Index'));
const VideoIndex = asyncComponent(() => import('./components/video/Index'));
const VideoDetail = asyncComponent(() => import('./components/video/Video'));
  1. .babelrc文件需要设置一下转换:
{
  "presets": [
    ["es2015"],
    "stage-1", // 应用了es7的语法,所以必须有这个配置
    "react",
    "env"
  ],
......
}

https://www.cnblogs.com/chris-oil/p/5717544.html

你可能感兴趣的:(#react懒加载引入组件)