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

背景

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

主要用到了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>
        ),
      },
    // 。。。。

配合路由表的完整例子

// 路由表
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;

效果
组件加载前
在这里插入图片描述
组件懒加载后
在这里插入图片描述
这样就会大大加快首屏加载速度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 是一种优化技术,它可以帮助我们提高 React 应用程序的性能。当应用程序包含大量页面或组件时,使用可以减少初始时间并降低资源占用。 要实现,我们可以使用 React Router 库提供的 `React.lazy` 函数和 `Suspense` 组件。下面是一个示例: ```jsx import React, { lazy, Suspense } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; // 使用 React.lazy 定义需要组件 const Home = lazy(() => import('./Home')); const About = lazy(() => import('./About')); const Contact = lazy(() => import('./Contact')); function App() { return ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch> </Suspense> </Router> ); } export default App; ``` 在上面的示例中,我们首先使用 `React.lazy` 函数将要组件引入。然后,我们将这些组件用 `<Suspense>` 组件包裹,并设置一个 `fallback` 属性来定义在组件过程中显示的提示。最后,我们在 `<Switch>` 组件中使用 `<Route>` 来定义各个页面的径和对应的组件。 使用后,当用户访问到某个页面时,对应的组件才会被动态并渲染,从而提高了应用程序的速度和性能。 希望对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值