react错误边界

react实际运用中,为了防止某个组件的异常报错,导致整个程序都运行不起来,我们通常封装一个错误的组件:

import React from "react"

export default class ErrorBoundary extends React.Component{
    state = {
        hasError:false,
        error:null,
        errorInfo:null
    }

    /**
     * 子元素发生错误时触发
     */

    componentDidCatch(error,errorInfo){
        this.setState({
            hasError:true,
            error:error,
            errorInfo:errorInfo
        })
    }

    render(){
        if(this.state.hasError){
            return <div>{ this.props.render(this.state.error,this.state.errorInfo) }</div>
        }
        return this.props.children;
    }
}

调用,当组件出现错误时,加载render返回的内容

<ErrorBoundary render={ (error,errorInfo) => <p>{ '加载时发生错误' }</p> }>
   <Errors /> {/*出现错误的组件*/}
</ErrorBoundary>
原文地址:https://www.cnblogs.com/zhangrenjie/p/14070771.html