我们相信:世界是美好的,你是我也是。平行空间的世界里面,不同版本的生活也在继续...

react项目中,有很多类组件可以利用的生命周期,每个生命周期都有其各自的功能。在本文中,利用componentDidCatch来探讨一下react项目中类组件的错误信息捕捉的问题。虽然componentDidCatch也是和其它的生命周期是并列在一起的,但是实际的本文中的应用,是和目标组件不放在一起的。父组件捕捉子组件的错误,所以,componentDidCatch是放在父组件里面的。

苏南大叔:react教程,如何利用componentDidCatch捕捉错误信息? - react-捕捉错误信息
react教程,如何利用componentDidCatch捕捉错误信息?(图5-1)

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述reactcomponentDidCatch生命周期的使用方式方法。本文测试环境:create-react-app@5.0.1react@18.2.0react-dom@18.2.0node@16.14.2

子组件抛出异常

这里描述子组件如何抛出错误,有两种情况。
第一种,自然触发的逻辑错误。例如:

let arr = ["苏南大叔"]
let target = arr[3].toString()

第二种,主动抛出的错误逻辑。例如:

throw new Error('发生了错误');

苏南大叔:react教程,如何利用componentDidCatch捕捉错误信息? - 抛出错误
react教程,如何利用componentDidCatch捕捉错误信息?(图5-2)

Child.js

import React, { Component } from 'react'
export default class index extends Component {
  constructor(props) {
    super(props);
  }
  componentDidCatch(error, info) {
    console.log("捕捉不到自己的错误");
  }
  render() {
    throw new Error('发生了错误');
    let arr = ["苏南大叔"]
    let target = arr[3].toString()
    return (
      <div>没发生错误</div>
    )
  }
}

父组件捕获异常

父组件中使用componentDidCatch来捕获上述子组件中的异常信息。

componentDidCatch(error, stack) {
  // 错误信息error.message/error.toString()
  // 错误堆栈error.stack
  // 组件堆栈stack.componentStack
  this.setState({
    error,
    stack
  })
}

父组件中根据是否发生错误,来决定render什么内容。如果没有错误,则执行下面的代码即可。

return this.props.children;

苏南大叔:react教程,如何利用componentDidCatch捕捉错误信息? - 父组件捕获错误
react教程,如何利用componentDidCatch捕捉错误信息?(图5-3)

CatchError.js

import React, { Component } from 'react';
class CatchError extends Component {
  constructor(props) {
    super(props)
    this.state = {
      error: false,
      stack: ''
    }
  }
  componentDidCatch(error, stack) {
    // 错误信息error.message/error.toString()
    // 错误堆栈error.stack
    // 组件堆栈stack.componentStack
    this.setState({
      error,
      stack
    })
  }
  render() {
    if (this.state.error) {
      return (
        <div>
          <div>错误:{this.state.error.message}</div>
          <div>位置:{this.state.stack.componentStack}</div>
        </div>
      )
    }
    return this.props.children;
  }
}
export default CatchError;

父组件包裹子组件

通过包裹子组件,来把错误信息控制在一定范围内,而不影响外部的UI呈现。
App.js

import './App.css';
import { Routes, Route } from "react-router-dom";
import React from 'react';
import Child from './Child';
import CatchError from './CatchError';

function App() {
  return (
    <div className="App">
      <h1>公共部分,不会受影响</h1>
      <CatchError>
        <Routes>
          <Route index element={<Child />} />
        </Routes>
      </CatchError>
    </div>
  );
}
export default App;

苏南大叔:react教程,如何利用componentDidCatch捕捉错误信息? - 调用控制错误
react教程,如何利用componentDidCatch捕捉错误信息?(图5-4)

苏南大叔:react教程,如何利用componentDidCatch捕捉错误信息? - 运行结果截图
react教程,如何利用componentDidCatch捕捉错误信息?(图5-5)

相关链接

结束语

更多react经验文章,请点击苏南大叔的博客文章:

如果本文对您有帮助,或者节约了您的时间,欢迎打赏瓶饮料,建立下友谊关系。
本博客不欢迎:各种镜像采集行为。请尊重原创文章内容,转载请保留作者链接。

 【福利】 腾讯云最新爆款活动!1核2G云服务器首年50元!

 【源码】本文代码片段及相关软件,请点此获取更多信息

 【绝密】秘籍文章入口,仅传授于有缘之人   react