MST

星途 面试题库

面试题:React中错误处理生命周期方法的基本使用

在React组件中,列举出用于错误处理的生命周期方法,并简述它们在捕获错误时的作用范围和时机。同时,用代码示例展示如何在一个简单的React组件中使用这些方法来捕获子组件渲染、生命周期方法或构造函数中抛出的错误。
41.5万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

用于错误处理的生命周期方法

  1. componentDidCatch(error, errorInfo)
    • 作用范围:用于捕获子组件树中任何位置抛出的错误,包括子组件的渲染、生命周期方法以及构造函数中的错误。但不会捕获自身组件抛出的错误。
    • 时机:在子组件树抛出错误后,会在渲染阶段、生命周期方法和构造函数之后被调用。
  2. static getDerivedStateFromError(error)
    • 作用范围:同样捕获子组件树中抛出的错误,不捕获自身组件错误。
    • 时机:在组件捕获到错误后,渲染阶段调用,可用于更新 state 以反映错误状态。

代码示例

import React, { Component } from'react';

class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false
        };
    }

    componentDidCatch(error, errorInfo) {
        // 记录错误信息,可用于日志上报等
        console.log('Error caught in componentDidCatch:', error, errorInfo);
        this.setState({ hasError: true });
    }

    static getDerivedStateFromError(error) {
        // 这里可以返回新的 state 以告知 UI 发生了错误
        console.log('Error caught in getDerivedStateFromError:', error);
        return { hasError: true };
    }

    render() {
        if (this.state.hasError) {
            return <div>There was an error in a child component.</div>;
        }
        return this.props.children;
    }
}

class ChildComponent extends Component {
    constructor(props) {
        super(props);
        // 模拟构造函数抛出错误
        throw new Error('Constructor error in ChildComponent');
    }

    render() {
        return <div>Child component content</div>;
    }
}

class App extends Component {
    render() {
        return (
            <ErrorBoundary>
                <ChildComponent />
            </ErrorBoundary>
        );
    }
}

export default App;

在上述代码中,ErrorBoundary 组件通过 componentDidCatchstatic getDerivedStateFromError 方法捕获 ChildComponent 构造函数中抛出的错误,并在 ErrorBoundaryrender 方法中根据错误状态展示不同的 UI。