MST

星途 面试题库

面试题:React高阶组件封装错误边界逻辑的基础实现

请简述如何使用高阶组件封装React中的错误边界逻辑,并且给出一个简单的代码示例,包括错误边界处理组件内部生命周期方法在捕获错误时的执行逻辑。
42.4万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

简述使用高阶组件封装React错误边界逻辑的方法

  1. 定义错误边界组件:创建一个类组件作为错误边界,该组件需要实现 componentDidCatch 生命周期方法,用于捕获子组件树中的JavaScript错误。
  2. 创建高阶组件:定义一个函数,该函数接收一个组件作为参数,并返回一个新的组件。在新组件内部,渲染传入的组件,并将其包裹在错误边界组件中。

代码示例

import React, { Component } from 'react';

// 错误边界组件
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
      errorInfo: null
    };
  }

  componentDidCatch(error, errorInfo) {
    // 捕获到错误时执行的逻辑
    console.log('捕获到错误:', error, errorInfo);
    this.setState({
      hasError: true,
      error,
      errorInfo
    });
  }

  render() {
    if (this.state.hasError) {
      // 展示错误信息
      return (
        <div>
          <h2>发生错误:</h2>
          <p>{this.state.error.message}</p>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      );
    }
    return this.props.children;
  }
}

// 高阶组件
function withErrorBoundary(WrappedComponent) {
  return function(props) {
    return (
      <ErrorBoundary>
        <WrappedComponent {...props} />
      </ErrorBoundary>
    );
  };
}

// 示例组件
class ExampleComponent extends Component {
  render() {
    throw new Error('模拟错误');
    return <div>这是示例组件</div>;
  }
}

// 使用高阶组件包裹示例组件
const EnhancedExampleComponent = withErrorBoundary(ExampleComponent);

// 应用组件
class App extends Component {
  render() {
    return (
      <div>
        <EnhancedExampleComponent />
      </div>
    );
  }
}

export default App;

错误边界处理组件内部生命周期方法在捕获错误时的执行逻辑

  1. componentDidCatch:当子组件树中抛出未捕获的JavaScript错误时,该方法会被调用。参数 error 是实际抛出的错误对象,errorInfo 包含有关错误发生位置的组件堆栈信息。在这个方法中,可以进行错误日志记录、通知监控系统等操作,并通过 setState 更新错误边界组件的状态,以便展示错误信息给用户。同时,React会停止渲染当前错误组件及其子组件,并展示错误边界组件返回的内容。