性能优化-react路由懒加载和组件懒加载

背景

随着项目越来越大,打包后的包体积也越来越大,严重影响了首屏加载速度,需要对路由和组件做懒加载处理

主要用到了react中的lazy和Suspense。

废话不多说,直接上干货

路由懒加载

核心代码

js 复制代码
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>
        ),
      },
    // 。。。。

配合路由表的完整例子

js 复制代码
// 路由表
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 };

组件懒加载

js 复制代码
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;

效果

组件加载前

组件懒加载后

这样就会大大加快首屏加载速度

相关推荐
Ciito2 分钟前
将 Element UI 表格元素导出为 Excel 文件(处理了多级表头和固定列导出的问题)
前端·vue.js·elementui·excel
不爱吃饭爱吃菜1 小时前
uniapp微信小程序一键授权登录
前端·javascript·vue.js·微信小程序·uni-app
heart000_11 小时前
从零开始打造个人主页:HTML/CSS/JS实战教程
javascript·css·html
90后小陈老师2 小时前
3D个人简历网站 5.天空、鸟、飞机
前端·javascript·3d
chenbin___2 小时前
react native text 显示 三行 超出部分 中间使用省略号
javascript·react native·react.js
漫路在线6 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
不爱吃糖的程序媛6 小时前
浅谈前端架构设计与工程化
前端·前端架构设计
BillKu7 小时前
Vue3 Element Plus 对话框加载实现
javascript·vue.js·elementui
郝YH是人间理想7 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core7 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows