React in suspense and lazy

React the components are introduced usually generally:

import Demo from "../pages/Demo/Demo";

  Note: import ... must be written at the top of the file, or will be error

We can also use lazy loading method React.lazy provides dynamic load components, such as:

import React, { lazy, Suspense } from 'react';

const MyEcharts = lazy(() => import("../pages/Demo/compontent/MyEcharts"));
Prior to loading is complete, add a loading animation:
  With lazy loading React.lazy, if need be loaded again in a movie, it is necessary to use Suspense.
  fallback method Suspense component for component does not load the page displayed when complete, you can better interact.
<React.Suspense fallback = { 'Loading'}>
    <OtherComponent />
</React.Suspense>
For complete router.js example:
import React, { lazy, Suspense } from 'react';
import { Route, Switch } from "react-router-dom";
// import Demo from "../pages/Demo/Demo";
const Demo = lazy(() => import("../pages/Demo/Demo"));
// import CssIndex from "../pages/CSSAbout/CssIndex";
const CssIndex = lazy(() => import("../pages/CSSAbout/CssIndex"));
// import MyEcharts from "../pages/Demo/compontent/MyEcharts";
const MyEcharts = lazy(() => import("../pages/Demo/compontent/MyEcharts"));
// import loading from "../assets/imgs/日历1.png";
const loading = require("../assets/imgs/loading.png");

let routerData = [
  {
    path:'/',
    component: CssIndex
  },
  {
    path:'/CssIndex',
    component: CssIndex
  },
  {
    path:'/MyDatePicker',
    component: Demo
  },
  {
    path:'/MyEcharts',
    component: MyEcharts
  }
];

function SubRoute() {
  return (
      <Switch>
      {
        routerData.map((e,i)=>{
          return <Route exact path={e.path} component={WaitingCompontent(e.component)} key={i}/>
        })
      }
      </Switch>
  )
}

function WaitingCompontent(WarpComponent) {
  return props => {
    return (
      <Suspense fallback={<img src={loading} alt="" className="page-loading" />}>
        <WarpComponent {...props} />
      </Suspense>
    )
  }
}

export {
  SubRoute,
  routerData
};

 

Guess you like

Origin www.cnblogs.com/MrZhujl/p/12463419.html