lazy/Suspense 与 路由懒加载

介绍

import Loading from "./15.Loading";
const MainComponent = React.lazy(() => import('./15.Main.jsx'));
const Main2Component = React.lazy(() => import('./15.Main2.jsx'));

class App extends React.Component {
  render() {
    return (
      <React.Suspense fallback={ <Loading /> }>
        <MainComponent />
        <Main2Component />
      </React.Suspense>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
class Loading extends React.Component {
  render() {
    return <div>Loading...</div>
  }
}
export default Loading;
class Main extends React.Component {
  render() {
    return <div>Main</div>
  }
}
export default Main;
class Main2 extends React.Component {
  render() {
    return <div>Main2</div>
  }
}
export default Main2

路由懒加载

import React, { Component, lazy, Suspense } from 'react';
import Loading from './Loading.jsx';

import { Switch, Route } from 'react-router';

const MainComponent = lazy(() => import('./Main.jsx'));

class App extends Component {
  render() {
      return (
        <div className="App">
          <Suspense fallback={ <Loading /> }>
            <Switch>
              <Route path="/page1" component={ lazy(() => import('./views/Page1')) } />
              <Route path="/page2" component={ lazy(() => import('./views/Page2')) } />
              <Route path="/page3" component={ lazy(() => import('./views/Page3')) } />
            </Switch>
          </Suspense>
        </div>
      );
  }
}
export default App;
import React from 'react';
class Main extends React.Component {
  render() {
    return <div>Main</div>
  }
}
export default Main;
import React from 'react';
class Loading extends React.Component {
  render() {
    return <div>Loading</div>
  }
}
export default Loading;
import React, { Component} from 'react';

class Page1 extends Component {
  render() {
    return <div>Page1</div>
  }
}
export default Page1;