React+TS前台项目实战(二)-- 路由配置 + 组件懒加载 + Error Boundary使用

文章目录


前言

本文将详细介绍项目中的页面路由配置和异步组件懒加载处理,以提高用户体验,实现过渡效果。


一、路由配置和懒加载lazy的使用

(1)在React中,通常使用Suspense和lazy函数来实现懒加载,比如使用一个加载动画。

(2)通过这种方式,可以减少初始加载时间,提高应用程序的性能和响应速度。

c 复制代码
// @/router/index.ts
import { lazy } from "react";
import { Navigate, RouteObject } from "react-router-dom";
const Layout = lazy(() => import("@/layout"));
const NotFound = lazy(() => import("@/pages/NotFound/index"));
const Home = lazy(() => import("@/pages/Home"));
const NervosDao = lazy(() => import("@/pages/NervosDao"));
const Tokens = lazy(() => import("@/pages/Tokens"));
const Xudts = lazy(() => import("@/pages/Xudts"));
const Charts = lazy(() => import("@/pages/Charts"));
const FeeRateTracker = lazy(() => import("@/pages/FeeRateTracker"));
const routes: RouteObject[] = [
  {
    path: "/",
    element: <Navigate to={`/zh/home`} />,
  },
  {
    path: "/:locale",
    element: <Navigate to={`/zh/home`} />,
  },
  {
    path: "/:locale",
    element: <Layout />,
    children: [
      // 其他子路由配置
      {
        path: "/:locale/home",
        element: <Home />,
      },
      {
        path: "/:locale/nervosdao",
        element: <NervosDao />,
      },
      {
        path: "/:locale/tokens",
        element: <Tokens />,
      },
      {
        path: "/:locale/xudts",
        element: <Xudts />,
      },
      {
        path: "/:locale/charts",
        element: <Charts />,
      },
      {
        path: "/:locale/fee-rate-tracker",
        element: <FeeRateTracker />,
      },
    ],
  },
  {
    path: "/404",
    element: <NotFound />,
  },
  {
    path: "*",
    element: <Navigate to={`/404`} />,
  },
];
export default routes;

二、TS版本Error Boundary组件封装

c 复制代码
// @/components/ErrorBoundary/index.jsx
import * as React from "react";
interface PropsType {
  children: React.ReactNode;
}
interface StateType {
  hasError: boolean;
  Error?: null | Error;
  ErrorInfo?: null | React.ErrorInfo;
}
export class ErrorBoundary extends React.Component<PropsType, StateType> {
  constructor(props: PropsType) {
    super(props);
    this.state = {
      hasError: false,
      Error: null,
      ErrorInfo: null,
    };
  }
  //控制渲染降级UI
  static getDerivedStateFromError(error: Error): StateType {
    return { hasError: true };
  }
  //捕获抛出异常
  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    //传递异常信息
    this.setState((preState) => ({ hasError: preState.hasError, Error: error, ErrorInfo: errorInfo }));
    //可以将异常信息抛出给日志系统等等
    //do something....
  }
  render() {
    const { hasError, Error, ErrorInfo } = this.state;
    const { children } = this.props;
    //如果捕获到异常,渲染降级UI
    if (hasError) {
      return (
        <div>
          <h1>{`Error:${Error?.message}`}</h1>
          <details style={{ whiteSpace: "pre-wrap" }}>{ErrorInfo?.componentStack}</details>
        </div>
      );
    }
    return children;
  }
}

三、在layout组件中使用Suspense组件和错误边界组件

c 复制代码
// @/layout/index.tsx
import { Suspense } from "react";
import { ErrorBoundary } from "@/components/ErrorBoundary";
const LayOut = () => {
  // ....
  return (
    // ...
    <Suspense fallback={<span>loading...</span>}>
      <ErrorBoundary>
        <Outlet />
      </ErrorBoundary>
    </Suspense>
    // ...
  );
};
export default LayOut;

总结

下一篇讲【国际化配置】。关注本栏目,将实时更新。

相关推荐
郑洁文29 分钟前
基于Python的Web命令执行漏洞自动化检测系统
前端·python·网络安全·自动化
新酱爱学习38 分钟前
手搓 10 个 Skill 后,我把重复劳动收敛成了一套零依赖 CLI 工具
前端·javascript·人工智能
IT_陈寒1 小时前
Python的线程池居然把我坑在了垃圾回收这块
前端·人工智能·后端
研☆香1 小时前
es6新特性功能介绍(一)
前端·ecmascript·es6
陈_杨2 小时前
鸿蒙开发-疾阅App阅读训练功能技术解析
前端·javascript
zhangxingchao2 小时前
AI应用开发八:RAG相关技术总结
前端·人工智能·后端
凌涘2 小时前
依托 BEM 规范深度剖析 WeUI 微信按钮组件开发与实现
前端·微信
小KK_2 小时前
CSS浮动布局指南:从文档流到BFC
前端·css·html
Hommy882 小时前
【剪映小助手】音频处理接口
前端·音视频·剪映小助手·视频剪辑自动化