路由的懒加载:将路由组件进行分包。可以提升首页的加载速度,提高用户的转化率。
引入
import React, {lazy,Suspense} from 'react';
import {BrowserRouter as Router, NavLink, Route} from "react-router-dom"
const One = lazy(() => import ("./pages/One"));
const Two = lazy(() => import ("./pages/Two"));
const Three = lazy(() => import ("./pages/Three"));
使用/*webpackChunkName:"名称"*/给要加载的模块取别名
const One = lazy(() => import (/*webpackChunkName:"one"*/"./pages/One"));
const Two = lazy(() => import (/*webpackChunkName:"two"*/"./pages/Two"));
const Three = lazy(() => import (/*webpackChunkName:"three"*/"./pages/Three"));
lazy方法需要与Suspense组件结合使用。Suspense属性:fallback值是一个组件
<Router>
<NavLink to={"/"} exact>one</NavLink>
<NavLink to={"/two"}>two</NavLink>
<NavLink to={"/three"}>three</NavLink>
<Suspense fallback={<p>加载中......</p>}>
<Route path={"/"} component={One} exact></Route>
<Route path={"/two"} component={Two}></Route>
<Route path={"/three"} component={Three}></Route>
</Suspense>
</Router>