React series (23) lazy loading application

In the React project created with Create React App, the required components are usually referenced by import (such as import HelloWorld from './HelloWorld'). When the project is packaged into production environment code, the js files referenced in this way will be Pack it together. When the code size of the front-end project is large enough, it means that the final packaged index.js code size will also be very large, which is obviously not conducive to the second loading of the page. In this scenario, lazy loading provides a solution. The root of lazy loading is code splitting, which can independently split the component code that does not need to be displayed on the first screen into a file, and then dynamically load such components at an appropriate time (such as after user interaction).

React implements lazy loading in two ways:

1. import().then();

import("./math").then(math => {
  console.log(math.add(16, 26));
});

Taking the code as an example, the method is used to realize lazy loading. When packaging, the content of import, namely math.

In practical applications, it is often encapsulated into a dynamically loaded higher-order component asyncComponent:

import React, { Component } from 'react';
 
const asyncComponent = (importComponent) => {
  return class extends Component {
    constructor() {
      super();
      this.state = {
        component: null
      };
    }
    componentDidMount() {
      importComponent()
        .then(cmp => {
          this.setState({ component: cmp.default });
        });
    }
    render() {
      const C = this.state.component;
      return C ? <C {...this.props} /> : null;
    }
  };
};
 
export default asyncComponent;

Lazy loading implementation of asyncComponent applied to routing:

<Switch>
    <Route exact path="/" component={AsyncComponent(() => import('./routes/Home'))}></Route>
    <Route path="/about" component={AsyncComponent(() => import('./routes/About'))}></Route>
</Switch>

2.React.lazy

React.lazy accepts a function that calls import() dynamically. It must return a Promise that needs to resolve a React component that defalut exports. React.lazy is often used in conjunction with React.Suspense.

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

const CompA = lazy(() => import('./CompA'));
class Test extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        const visible = false;
        return (
            <div>
                {visible ?
                    <Suspense fallback={<div>Loading...</div>}>
                        <CompA />
                    </Suspense> : null}
            </div>
        );
    }
}

export default Test;

In the above code, the component CompA will not be loaded immediately, but will be dynamically loaded only when visible is true.

When the project is packaged, the same as the first method, CompA.js will be packaged independently, and the packaged file will be referenced to the project through dynamic loading.

React.lazy is applied to route lazy loading implementation:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

 

Guess you like

Origin blog.csdn.net/zeping891103/article/details/104777436