在路由组件使用懒加载的方式,可以优化性能,加载哪个组件就用哪个组件
1.首先需要引入lazy组件
2.引入组件时用调用lazy方法,传递进入一个函数
3.使用Suspense将路由组件包裹
4.Suspense中使用一个 fallback属性作为懒加载的加载中的组件
import React, { Component, lazy, Suspense } from "react";
import { NavLink, Route } from "react-router-dom";
// import Home from './components/Home'
import Loading from './components/Loading'
const Home = lazy(() => import("./components/Home"));
const About = lazy(() => import("./components/About"));
class App extends Component {
render() {
return (
<div>
<div className="box">
<div className="box_list">
<div>
<NavLink to="/home"> 主页</NavLink>
</div>
<div>
<NavLink to="/about">关于</NavLink>
</div>
</div>
<div className="box_content">
<Suspense fallback={<Loading></Loading>}>
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
</Suspense>
</div>
</div>
</div>
);
}
}
export default App;