面试题答案
一键面试componentDidCatch
生命周期函数参数含义
error
:该参数是一个Error
对象,代表在渲染、生命周期方法,或子组件的构造函数中抛出的错误。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 平台上进行错误分析和跟踪。