在路由组件使用懒加载的方式,可以优化性能,加载哪个组件就用哪个组件

    1. 1.首先需要引入lazy组件
    2. 2.引入组件时用调用lazy方法,传递进入一个函数
    3. 3.使用Suspense将路由组件包裹
    4. 4.Suspense中使用一个 fallback属性作为懒加载的加载中的组件
    1. import React, { Component, lazy, Suspense } from "react";
    2. import { NavLink, Route } from "react-router-dom";
    3. // import Home from './components/Home'
    4. import Loading from './components/Loading'
    5. const Home = lazy(() => import("./components/Home"));
    6. const About = lazy(() => import("./components/About"));
    7. class App extends Component {
    8. render() {
    9. return (
    10. <div>
    11. <div className="box">
    12. <div className="box_list">
    13. <div>
    14. <NavLink to="/home"> 主页</NavLink>
    15. </div>
    16. <div>
    17. <NavLink to="/about">关于</NavLink>
    18. </div>
    19. </div>
    20. <div className="box_content">
    21. <Suspense fallback={<Loading></Loading>}>
    22. <Route path="/home" component={Home} />
    23. <Route path="/about" component={About} />
    24. </Suspense>
    25. </div>
    26. </div>
    27. </div>
    28. );
    29. }
    30. }
    31. export default App;