安装 React 路由依赖

  1. npm inistall react-router react-router-dom -S

配置路由懒加载

index.jsx

  1. import React from 'react';
  2. import React from 'react-dom';
  3. import App from './App';
  4. import {BrowserRouter} from './react-router-dom';
  5. ReactDOM.render(
  6. <BrowserRouter>
  7. <App />
  8. </BrowserRouter>,
  9. document.getElementById('root')
  10. );

App.jsx

  1. import React, {Component, lazy, Suspense} from 'react';
  2. import Loading from './loading';
  3. import {Switch, Route} from 'react-router';
  4. class App extends Component{
  5. render(){
  6. return (
  7. <Suspense fallback={<Loading />}>
  8. <div className="app">
  9. <Switch>
  10. <Route path="/page1" component={lazy(() => import('./views/Page1'))}/>
  11. <Route path="/page2" component={lazy(() => import('./views/Page2'))}/>
  12. <Route path="/page3" component={lazy(() => import('./views/Page3'))}/>
  13. </Switch>
  14. </div>
  15. </Suspense>
  16. )
  17. }
  18. }