React-错误边界

React-错误边界

  • 错误边界是用于捕获其子组件树 JavaScript 异常,记录错误并展示一个回退的 UI 的 React 组件,而不是整个组件树的异常。错误边界在渲染期间、生命周期方法内、以及整个组件树构造函数内捕获错误.

  • 注意: 错误边界无法捕获以下几个错误。
    (1).事件处理
    (2).错误边界组件自身的错误
    (3).异步代码(setTimeout 或 requestAnimationFrame 回调函数)
    (4).服务端渲染

  • 如果一个 class 组件中定义了 static getDerivedStateFromError() 或 componentDidCatch() 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。

  • 使用示例

//创建一个 错误边界(组件)
class ErrorBoundary extends React.Component {
	constructor(props){
		super(props);
		this.state = {
			error:null,
			errorInfo:null
		}
	};
	compontDidCatch(error,errorInfo){      // 错误边界特有的函数
		this.setState({
			error:error,
			errorInfo:errorInfo
		})
	}
	render(){
		if(this.state.errorInfo){
			return (
				<div>
					<h2>Have something error</h2>
					<details>
						<p>{this.state.error && this.state.error.toString()}</p>
						<p>{this.state.errorInfo.compontStack}</p>
					</details>
				</div>
			)
		}
	}
}

class Person extends React.Component {
	constructor(props){
		super(props);
		this.state = {
			count:0
		}
	}
	addCount(){
		this.setState((state,props)=>({
			count:++state.count
		}));
	}
	render(){
		if(this.state.count === 5){
			throw new Error('The number property cannot be greater than 5');
		}
		return (
			<div>
				<h2>这是错误边界 测试</h2>
				<p onClick={this.addCount.bind(this)}>{this.state.count}</p>
			</div>
		)
	}
}
ReactDOM.render(
	<div>
		<ErrorBoundary >
			<Person />
		</ErrorBoundary >
	</div>
);
  • 当有错误抛出的时候,就会渲染错误边界组件内的错误信息。
    在这里插入图片描述
发布了96 篇原创文章 · 获赞 64 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41709082/article/details/103804469