Add the following to src/components/AsyncComponent.js.
高级组件
[cc lang=”javascript”]
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 ? 
    }
  }
  return AsyncComponent;
}[/cc]
Use it
[cc lang=”javascript”]const AsyncHome = asyncComponent(() => import(“./containers/Home”));[/cc]
in your rooter
[cc lang=”javascript”]
import React from “react”;
import { Route, Switch } from “react-router-dom”;
import asyncComponent from “./components/AsyncComponent”;
import AppliedRoute from “./components/AppliedRoute”;
import AuthenticatedRoute from “./components/AuthenticatedRoute”;
import UnauthenticatedRoute from “./components/UnauthenticatedRoute”;
const AsyncHome = asyncComponent(() => import(“./containers/Home”));
const AsyncLogin = asyncComponent(() => import(“./containers/Login”));
const AsyncNotes = asyncComponent(() => import(“./containers/Notes”));
const AsyncSignup = asyncComponent(() => import(“./containers/Signup”));
const AsyncNewNote = asyncComponent(() => import(“./containers/NewNote”));
const AsyncNotFound = asyncComponent(() => import(“./containers/NotFound”));
export default ({ childProps }) =>
  
    
    
    
    
    
    {/* Finally, catch all unmatched routes */}
    
  
;[/cc]
可以用 react-loadable 代替
[cc lang=”javascript”]const AsyncHome = Loadable({
  loader: () => import(“./containers/Home”),
  loading: MyLoadingComponent
});
const MyLoadingComponent = ({isLoading, error}) => {
  // Handle the loading state
  if (isLoading) {
    return 
;
  }
  // Handle the error state
  else if (error) {
    return 
;
  }
  else {
    return null;
  }
};[/cc]