本篇内容介绍了“react lazyLoad加载如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
1.lazyLoad用处
默认例如首页,如果有好十几个甚至百个路由,react是会默认一下全部把路由组件一下全部加载的,极可能造成页面卡顿。react lazyLoad就可以解决这个问题。
2.使用
我用的react版本是18,注意在主index.js中<React.StrictMode>要去掉,不然会出现路由变化了,控制台也不报错但是页面不跳转的问题.
2.1 react-router-dom5版本写法
import React, { Component,lazy,Suspense} from 'react'import {NavLink,Route} from 'react-router-dom'import Loading from './Loading'const Home = lazy(()=> import('./Home') )const About = lazy(()=> import('./About'))export default class Demo extends Component {render() {return (<div><div className="row"><div className="col-xs-offset-2 col-xs-8"><div className="page-header"><h3>React Router Demo</h3></div></div></div><div className="row"><div className="col-xs-2 col-xs-offset-2"><div className="list-group">{}<NavLink className="list-group-item" to="/about">About</NavLink><NavLink className="list-group-item" to="/home">Home</NavLink></div></div><div className="col-xs-6"><div className="panel"><div className="panel-body"> {}<Suspense fallback={<Loading/>}>{}<Route path="/about" component={About}/><Route path="/home" component={Home}/></Suspense></div></div></div></div></div>)}}
2.2 react-router-dom6版本写法
主要是引入和Suspense的改变
import React, { Component, lazy, Suspense } from "react";import { NavLink, Route,Routes } from "react-router-dom";import Loading from "./Loading";const Home = lazy(() => import("./Home"));const About = lazy(() => import("./About"));export default class Demo extends Component { render() { return ( <div> <div className="row"> <div className="col-xs-offset-2 col-xs-8"> <div className="page-header"> <h3>React Router Demo</h3> </div> </div> </div> <div className="row"> <div className="col-xs-2 col-xs-offset-2"> <div className="list-group"> {} <NavLink className="list-group-item" to="/about"> About </NavLink> <NavLink className="list-group-item" to="/home"> Home </NavLink> </div> </div> <div className="col-xs-6"> <div className="panel"> <div className="panel-body"> {} <Suspense fallback={<Loading />}> {} <Routes> <Route path="/about" element={<About/>} /> <Route path="/home" element={<Home/>} /> </Routes> </Suspense> </div> </div> </div> </div> </div> ); }}
需要注意的是,lazyLoad只有在第一次请求那个路由组件才会去调用资源请求,第二次就不会再去调用的了,有缓存。
“react lazyLoad加载如何使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!