Skip to main content

ErrorBoundaries 原理

import React from 'react'
import ProTypes from 'prop-types'

class ErrorBoundary extends React.Component {
static propTypes = {
child:PropTypes.object
}
// 是否出错
state = {
hasError:false
}
// 生命周期:捕获错误信息
componentDidCatch(error,info){
this.setState({
hasError:true
})
error.message = `${error.message}`
console.error('error',error);
// 上报错误
if (window && window.BJ_REPORT) window.BJ_REPORT.report(error, false, 'ui');
}
render(){
const {hasError} = this.state

// 出错返回空字符
if(hasError)return ''

return this.props.children
}
}

const errorBoundary = WrappedComponent => {
// 浅比较组件
return class extends React.PureComponent {
render(){
return (
<ErrorBoundary>
<WrappedComponent
{this.props} // 参数
/>
</ErrorBoundary>
)
}
}
}

// 两种方式可引入
export { errorBoundary }
export default errorBoundary