React extension 2 - lazyLoad of routing components

lazyLoad lazy loading: load when needed
  • When lazy loading is not used, all routing components are loaded to the page as soon as the page is opened
  • If there are many routing components, and users will not actually access so many routing components, then it is equivalent to loading unnecessary redundant components
  • Therefore, lazy loading of routes can be used, and requests are made when users really need access
import {lazy, Suspense} from 'react'
import {Route} from 'react-router-dom'

//Loading是一般组件,不需要懒加载
import Loading from './Loading'
//1.通过React的lazy函数配合import()函数动态加载路由组件 ===> 路由组件代码会被分开打包
const Home = lazy(()=>import('./home'))
const About = lazy(()=>import('./about'))

...
render () {
	return (
		...
        //2.通过<Suspense>指定在加载得到路由打包文件前显示一个自定义loading界面
		<!-- 当组件正在加载时,显示 Loading -->
		<Suspense fallback={<h1>Loading...</h1>}>
			<Route path="/home" component={Home} />
			<Route path="/about" component={About} />
		</Suspense>
		...
	)
}
...

Comparison before and after lazy loading:

  • Lazy loading is not used: the opened page has been loaded, and the click route does not request resources

  • Use lazy loading: click on the route and then request resources for loading

The role of Suspense: give a prompt when loading is slow

  • When a custom loading interface specified by Suspense is a label

  • When a custom loading interface specified by Suspense is a component

Guess you like

Origin blog.csdn.net/m0_55990909/article/details/124377297