边界错误捕获

2020-06-22  本文已影响0人  skoll
// 错误边界

// 在子组件树的任何位置捕获js错误,记录这些错误,并显示一个备用ui,而不是整个组件树崩溃

// 无法捕获如下错误
// 1. 事件处理:事件内部的错误还是使用try catch
// 2. 异步代码 setTimeout
// 3. 服务端渲染
// 4. 错误边界自身抛出来的错误,仅仅能捕获子组件的错误,不能看到自身
// 5. 

import React from 'react'
class ErrorBoundar extends React.Component{
    constructor(props){
        super(props)
        this.state={hasError:false}
    }
    componentDidCatch(error,info){
        this.setState({hasError:true})
        console.log('发生了错误')
    }
    render(){
        if(this.state.hasError){
            return <h1>Something wnet wrong</h1>
        }
        return this.props.children
    }
}
上一篇 下一篇

猜你喜欢

热点阅读