- 当在某个组件出现错误时,整个网页都会报出错误提示
- 但这对用户来说是不友好的
- 因此,我们需要想办法,将错误限制在组件内,并且当错误发生时,进行替换显示
- 如下
import React, { Component } from 'react'
export default class A extends Component {
state = {error: ''}
static getDerivedStateFromError(error) {
return {error}
}
componentDidCatch() {
console.log('发生错误!')
}
render() {
return (
<div>
{}
{this.state.error ? <h1>发生错误</h1> : <B/>}
</div>
)
}
}
class B extends Component {
state = {msg: ''}
render() {
return (
<div>
{this.state.msg()} {}
</div>
)
}
}
ErrorBoundary
在开发模式不能体现出效果,需要打包之后查看