错误边界(Error Boundaries)

错误边界(Error Boundaries)

import React,{Component} from 'react';

class ErrorBoundary extends Component{
    constructor(props){
        super(props);
        this.state = {

        }
    }
    componentDidCatch(error,info){
        this.setState({
            error: error,
            errorInfo: info
        })
    }
    render(){
        if(this.state.errorInfo){
            return <h1>Something went wrong.</h1>
        }
        return this.props.children;
    }
}
export default ErrorBoundary;
import React,{Component} from 'react';
import ErrorBoundary from './../../components/ErrorBoundary';

function Example(){
    //throw new Error('I crashed!');
    //return <div>Ex</div>
}
class ErrorExample extends Component{
    render(){
        return(
            <ErrorBoundary>
                <Example/>
            </ErrorBoundary>
        )
    }
}
export default ErrorExample;

参考文章:https://www.jianshu.com/p/3ae9838ed51c
事件处理器如何处理?

class ErrorExample extends Component{
    constructor(props){
        super(props);
        this.state = {
            error: false
        }
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick=()=>{
        console.log('handleClick');
        try {
            // Do something that could throw
            throw new Error();
        } catch (error) {
            this.setState({ error });
        }
    }
    render(){
        if(this.state.error){
            return <h1>Caught an error.</h1>
        }
        return <div onClick={this.handleClick}>Click Me</div>
    }
}

export default ErrorExample;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值