15. react -- 错误处理


1. 错误边界解决什么问题:

  1. 解决错误边界组件内部子孙组件,出现加载错误【生命周期中】,用来优雅降级。显示错误边界组件提示的内容。

2. 错误边界无法捕获的场景:

  1. 自身错误

  2. 事件触发的错误

  3. 异步错误(定时器,requestAnimationFrame  或者 异步请求)

  4. 服务端渲染

3. 注意事项:

  1. 如果一个错误边界无法渲染错误信息,则错误会冒泡至最近的上层错误边界。类似与 try...catch...

  2. 开发模式启动,无法模拟错误捕获的场景,还是页面报错。build 后可以模拟该场景:

   npm i serve -g

   serve -s build  或者 serve -l 2000 -s build

  3. class 组件中定义了 static getDerivedStateFromError(error) 或 componentDidCatch(error) 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界

  4. 必须是 class 组件

4. 实例:

// ErrorBoundary.js 中
import React from 'react'
export default class ErrorBoundary extends React.Component {
    constructor (props) {
        super(props)
        this.state = {
            hasError: false
        }
    }

    static getDerivedStateFromError (error) {
        console.log(error, "getDerivedStateFromError")
        return { hasError: true }
    }

    componentDidCatch (error, errorInfo) {
        console.log(error, errorInfo, "componentDidCatch")
    }

    render () {
        if (this.state.hasError) {
            return (
出错了!
) } return this.props.children; } } // app.js 中 import ErrorBoundary from './ErrorBoundary' class User extends React.Component { constructor(props) { super(props) } componentDidMount () { } render () { // 设定一个错误 throw new Error('I crashed!'); return (
用户模块
) } } class App extends React.Component { constructor(props) { super(props) } render() { return ( ) } } ReactDOM.render( , document.getElementById('root') )