关于React错误边界
在未引入错误边界时,如果组件出现错误则会导致整个页面出现错误,对于用户非常不友好,因此有必要引入错误边界对可能出现错误的元素进行包裹
在React的生命周期函数中有一个componentDidCatch,它能够对子元素的错误进行捕获
componentDidCatch(error,errorInfo)
使用方法:单独创建一个错误边界组件
//ErrorBoundary.jsx
import React from 'react'
export default class ErrorBoundary extends React.Component{
constructor(){
super()
this.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;
}
}
在Home页面中引用ErrorBoundary,使用Errorboundary将可能出现错误的组件包裹
import Errorboundary from './Errorboundary.jsx'
import 可能出现错误的组件 from './可能出现错误的组件.jsx'
...
...
...
render(){
return(
<div>
<ErrorBoundary render{(error,errorInfo)=><p>{'组件发生错误'}</p>}>
<可能出现错误的组件/>
<ErrorBoundary>
</div>
)
}
此时出现错误的话则会在原本组件的位置提示:组件发生错误,
而其他组件依然能够正常运行