ReactJS 中的延迟加载
在本文中,我们将学习如何对我们应用程序的页面进行延迟加载,以使我们的 React 应用程序更加优化。
React 应用程序会在与制作 React 应用程序投入生产准备就绪之前,与预先安装的捆绑器(如 webpack)打包在一起。加载此已打包项目时,它会一次加载整个源代码,即使是用户很少访问的那些页面也是如此。因此,为了防止一次性加载整个应用程序,我们使用延迟加载的概念来缩短 DOM 加载时间,并提高应用程序的速度。
语法
const OtherComponent = React.lazy(() => import('./OtherComponent'));在此,OtherComponent 是将要延迟加载的组件。
示例
在此示例中,我们将构建一个加载组件的路由应用程序。
App.jsx
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react -router-dom';
const About = lazy(() => import('./About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/about" component={About} />
<Route
path="/"
exact
render={() => (
<div>
<h1>This is the main page</h1>
<a href="/about">Click here</a>
</div>
)}
/>
</Switch>
</Suspense>
</Router>
);
export default App;About.js
import React from 'react';
const About = () => {
return (
<div>
<h1>This is the about section</h1>
</div>
);
};
export default About;在以上示例中,当用户单击“单击此处”按钮时,about.js 脚本将延迟加载,并相应地更新 DOM。
输出
这将产生以下结果。

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP