React 错误边界组件 react-error-boundary 源码解析

本文主要是介绍React 错误边界组件 react-error-boundary 源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 捕获错误 hook
  • 创建错误边界组件 Provider
  • 定义错误边界组件
    • 定义边界组件状态
    • 捕捉错误
    • 渲染备份组件
    • 重置组件
    • 通过 useHook 控制边界组件

捕获错误 hook

  • getDerivedStateFromError
    • 返回值会作为组件的 state 用于展示错误时的内容
  • componentDidCatch

创建错误边界组件 Provider

  • 错误边界组件其实是一个通过 Context.Provider 包裹的组件,这样使得组件内部可以获取到捕捉的相关操作
import { createContext } from "react";export type ErrorBoundaryContextType = {didCatch: boolean;error: any;resetErrorBoundary: (...args: any[]) => void;
};// 错误边界组件其实是一个通过 Context.Provider 包裹的组件
export const ErrorBoundaryContext =createContext<ErrorBoundaryContextType | null>(null);

定义错误边界组件

定义边界组件状态

type ErrorBoundaryState =| {didCatch: true;error: any;}| {didCatch: false;error: null;};const initialState: ErrorBoundaryState = {didCatch: false, // 错误是否捕捉error: null, // 捕捉到的错误信息
};

捕捉错误

  • getDerivedStateFromError 捕捉到错误后,设置组件状态展示备份组件
  • componentDidCatch 用于触发错误回调
export class ErrorBoundary extends Component<ErrorBoundaryProps,ErrorBoundaryState
> {constructor(props: ErrorBoundaryProps) {super(props);this.resetErrorBoundary = this.resetErrorBoundary.bind(this);this.state = initialState;}static getDerivedStateFromError(error: Error) {return { didCatch: true, error };}componentDidCatch(error: Error, info: ErrorInfo) {this.props.onError?.(error, info);}}

渲染备份组件

  • 通过指定的参数名区分是无状态组件还是有状态组件
    • 无状态组件通过直接调用函数传递 props
    • 有状态组件通过 createElement 传递 props
  • 通过 createElement 处理传递的组件更加优雅
    • createElement(元素类型,参数,子元素)详情,其中第一个参数可以直接传递 Context.Provider
export class ErrorBoundary extends Component<ErrorBoundaryProps,ErrorBoundaryState
> {// ...render() {const { children, fallbackRender, FallbackComponent, fallback } =this.props;const { didCatch, error } = this.state;let childToRender = children;// 如果捕捉到了错误if (didCatch) {const props: FallbackProps = {error,resetErrorBoundary: this.resetErrorBoundary,};// 通过指定的参数名区分是无状态组件还是有状态组件if (typeof fallbackRender === "function") {childToRender = fallbackRender(props);} else if (FallbackComponent) {childToRender = createElement(FallbackComponent, props);} else if (fallback === null || isValidElement(fallback)) {childToRender = fallback;} else {if (isDevelopment) {console.error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");}throw error;}}// Context.Provider 可以直接作为 createElement 的第一个参数return createElement(ErrorBoundaryContext.Provider,{value: { // Context.Provider 提供可供消费的内容didCatch,error,resetErrorBoundary: this.resetErrorBoundary,},},childToRender);}// ...
}

重置组件

  • 将错误信息重置使得能渲染原组件
const initialState: ErrorBoundaryState = {didCatch: false, // 错误是否捕捉error: null, // 捕捉到的错误信息
};export class ErrorBoundary extends Component<ErrorBoundaryProps,ErrorBoundaryState
> {// ...resetErrorBoundary(...args: any[]) {const { error } = this.state;if (error !== null) {this.props.onReset?.({ // 触发对应回调args,reason: "imperative-api",});this.setState(initialState);}}// ...// 根据 resetKeys 重置,但并未对外暴露该 APIcomponentDidUpdate(prevProps: ErrorBoundaryProps,prevState: ErrorBoundaryState) {const { didCatch } = this.state;const { resetKeys } = this.props;// There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,// we'd end up resetting the error boundary immediately.// This would likely trigger a second error to be thrown.// So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.if (didCatch &&prevState.error !== null &&hasArrayChanged(prevProps.resetKeys, resetKeys)) {this.props.onReset?.({next: resetKeys,prev: prevProps.resetKeys,reason: "keys",});this.setState(initialState);}}
}function hasArrayChanged(a: any[] = [], b: any[] = []) {return (a.length !== b.length || a.some((item, index) => !Object.is(item, b[index])));
}

通过 useHook 控制边界组件

  • 通过 context 获取最近的边界组件内容
  • 通过手动抛出错误重新触发边界组件
import { useContext, useMemo, useState } from "react";
import { assertErrorBoundaryContext } from "./assertErrorBoundaryContext";
import { ErrorBoundaryContext } from "./ErrorBoundaryContext";type UseErrorBoundaryState<TError> =| { error: TError; hasError: true }| { error: null; hasError: false };export type UseErrorBoundaryApi<TError> = {resetBoundary: () => void;showBoundary: (error: TError) => void;
};export function useErrorBoundary<TError = any>(): UseErrorBoundaryApi<TError> {// 获取最近的边界组件 Provider 的内容const context = useContext(ErrorBoundaryContext);// 断言 Context 是否为空assertErrorBoundaryContext(context);const [state, setState] = useState<UseErrorBoundaryState<TError>>({error: null,hasError: false,});const memoized = useMemo(() => ({resetBoundary: () => {// 提供 Provider 对应的重置边界组件方法,渲染原组件context.resetErrorBoundary();setState({ error: null, hasError: false });},// 手动抛出错误,触发边界组件showBoundary: (error: TError) =>setState({error,hasError: true,}),}),[context.resetErrorBoundary]);// 当调用 showBoundary 后,该 hook 会手动抛出错误,让边界组件来捕捉if (state.hasError) {throw state.error;}return memoized;
}

这篇关于React 错误边界组件 react-error-boundary 源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/684127

相关文章

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

全面解析MySQL索引长度限制问题与解决方案

《全面解析MySQL索引长度限制问题与解决方案》MySQL对索引长度设限是为了保持高效的数据检索性能,这个限制不是MySQL的缺陷,而是数据库设计中的权衡结果,下面我们就来看看如何解决这一问题吧... 目录引言:为什么会有索引键长度问题?一、问题根源深度解析mysql索引长度限制原理实际场景示例二、五大解决

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现