MST

星途 面试题库

面试题:React错误边界的生命周期及实现细节

详细说明错误边界组件中componentDidCatch这个生命周期函数的参数含义,并举例说明如何在该函数中记录错误信息到外部服务,比如Sentry。
11.8万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

componentDidCatch 生命周期函数参数含义

  1. error:该参数是一个 Error 对象,代表在渲染、生命周期方法,或子组件的构造函数中抛出的错误。
  2. errorInfo:这是一个包含有关错误发生位置信息的对象。它通常包含 componentStack 属性,该属性是一个字符串,描述了错误发生时的组件栈信息,有助于定位错误发生的具体组件和调用栈。

举例说明如何在该函数中记录错误信息到外部服务(如 Sentry)

假设已经安装并配置好了 @sentry/react 库,以下是一个在 ErrorBoundary 组件中使用 componentDidCatch 记录错误到 Sentry 的示例:

import React, { Component } from 'react';
import * as Sentry from '@sentry/react';

class ErrorBoundary extends Component {
  componentDidCatch(error, errorInfo) {
    // 使用 Sentry.captureException 方法捕获错误并发送到 Sentry 服务
    Sentry.captureException(error, {
      extra: {
        errorInfo,
      },
    });
  }

  render() {
    return this.props.children;
  }
}

export default ErrorBoundary;

在上述代码中,componentDidCatch 方法捕获到错误后,通过 Sentry.captureException 将错误和额外的 errorInfo 信息发送到 Sentry 服务,便于在 Sentry 平台上进行错误分析和跟踪。