-
预先准备两个路由组件(Home组件和About组件)
javascriptimport React, { Component } from 'react export default class About extends Component { render() { return ( <div> about组件 </div> ) } }
javascriptimport React, { Component } from 'react' export default class Home extends Component { render() { return ( <div> home组件 </div> ) } }
-
准备一个普通组件(Loading组件)
javascriptimport React, { Component } from 'react' export default class Loading extends Component { render() { return ( <div> Loading... </div> ) } }
-
同文件夹下新建index.jsx文件
javascriptimport React, { Component, Suspense, lazy } from 'react' import { NavLink,Route} from 'react-router-dom' import Loading from './Loading' // 1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包 const Home = lazy(()=> import('./Home')) const About = lazy(()=> import('./About')) export default class lazyLoad extends Component { render() { return ( <div> <NavLink to='/home'>Home</NavLink> <NavLink to='/about'>About</NavLink> {/* 2.通过 <Suspense> 指定在加载得到路由打包文件前显示一个自定义loading界面 */} <Suspense fallback={<Loading/>}> <Route path='/home' component={Home}></Route> <Route path='/about' component={About}></Route> </Suspense> </div> ) } }
网速较慢时,可以看到loading组件效果。
react路由组件的lazyLoad
种草小幺儿.2023-11-09 15:08