react route load on demand

In a single page application, it is very necessary to load the route on demand. If all js are loaded at one time, with the rich functions of the application, the js file will increase, and the first download will slow down, affecting the user experience. This article shares the on-demand loading of the react router V4 version.

Asynchronously load wrapper components

First we need an asynchronous load wrapper component

import { Component } from 'react'

export default class Bundle extends Component {
  constructor(props) {
      super(props);
      this.state = {
          mod: null
      };
  }

  componentWillMount() {
      this.load(this.props)
  }

  componentWillReceiveProps(nextProps) {
      if (nextProps.load !== this.props.load) {
          this.load(nextProps)
      }
  }

  load(props) {
      this.setState({
          mod: null
      });
      //Note here that the Promise object is used; mod.default exports the default
      props.load().then((mod) => {
          this.setState({
              mod: mod.default ? mod.default : mod
          });
      });
  }

  render() {
      return this.state.mod ? this.props.children(this.state.mod) : null;
  }
}

Routing configuration

import React from 'react'
import {
  Route
} from 'react-router-dom'
import App from '../App'
import Bundle from '../components/Bundle'

const Find = (props) => (
  <Bundle load={() => import('../components/Find')}>
      {(Find) => <Find {...props}/>}
  </Bundle>
);
const Home = (props) => (
  <Bundle load={() => import('../containers/Home')}>
      {(Home) => <Home {...props}/>}
  </Bundle>
);

const routes = (
  <Route>
    <div>
    <Route path="/" component={App} />
    <Route path="/home" component={Home} />
    <Route path="/find" component={Find} />
    </div>
  </Route>
)

export default routes;

According to the above configuration, the on-demand loading of routing can be realized when the web pack is packed.

Tags: React

Posted on Fri, 01 May 2020 06:06:47 -0700 by verdrm