背景
隨著項目越來越大,打包后的包體積也越來越大,嚴重影響了首屏加載速度,需要對路由和組件做懶加載處理
主要用到了react中的lazy和Suspense。
廢話不多說,直接上干貨
路由懶加載
核心代碼
import React, { lazy, Suspense } from "react";
const loading = () => <h3>loading....</h3>;
const Caidan1 = lazy(() => import("@/pages/mud1/caidan1"));
const meunRoutes = [
{
name: "模塊1",
path: "/m1",
icon: <AppstoreOutlined />,
children: [
{
name: "gltf模型",
path: "/m1/caidan12",
icon: <AppstoreOutlined />,
element: (
<Suspense fallback={loading()}>
<Caidan1 />
</Suspense>
),
},
// 。。。。
配合路由表的完整例子文章來源:http://www.zghlxwxcb.cn/news/detail-625223.html
// 路由表
import React, { lazy, Suspense } from "react";
import Home from "../pages/home";
import Layout from "@/components/Layout";
const loading = () => <h3>loading....</h3>;
const Caidan1 = lazy(() => import("@/pages/mud1/caidan1"));
const Caidan2 = lazy(() => import("@/pages/mud1/caidan2"));
// 404頁面
const NotFound = () => <h1>**** 404 ****</h1>;
const meunRoutes = [
{
name: "模塊1",
path: "/m1",
icon: <AppstoreOutlined />,
children: [
{
name: "gltf模型",
path: "/m1/caidan12",
icon: <AppstoreOutlined />,
element: (
<Suspense fallback={loading()}>
<Caidan1 />
</Suspense>
),
},
{
name: "模型動畫",
path: "/m1/caidan13",
icon: <AppstoreOutlined />,
element: (
<Suspense fallback={loading()}>
<Caidan2 />
</Suspense>
),
},
],
},
];
// 配置路由表
const routes = [
{
path: "/",
element: <Navigate to="/home" />,
},
{
path: "/home",
element: <Home />,
},
{
path: "/",
element: <Layout />,
children: handleMenuRoutes(meunRoutes),
},
{ path: "*", element: <NotFound /> },
];
// 處理menu routes
function handleMenuRoutes(arr) {
let res = [];
arr.forEach((item) => {
if (item.children && item.children.length > 0) {
item.children.forEach((yitem) => {
let obj = {
path: yitem.path,
element: yitem.element,
};
res.push(obj);
});
}
});
return res;
}
const AppRouter = () => useRoutes([...routes]);
export { AppRouter, meunRoutes };
組件懶加載
import { useEffect, useState, lazy, Suspense } from "react";
const TestCpn = lazy(() => import("@/components/testCpn"));
const Home = () => {
const [show, setShow] = useState(false);
function fn() { setShow(true)}
return (
<div>
<button onClick={fn}>加載大組件</button>
{show && (
<Suspense>
<TestCpn />
</Suspense>
)}
</div>
);
};
export default Home;
效果
組件加載前
組件懶加載后
這樣就會大大加快首屏加載速度文章來源地址http://www.zghlxwxcb.cn/news/detail-625223.html
到了這里,關(guān)于性能優(yōu)化-react路由懶加載和組件懶加載的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!