React组件错误(error)收集方法

React组件错误(error)收集方法

1、添加错误状态变量

	在state中添加error变量,初始化为null。
	this.state = { error : null }

2、结合使用catch和setState()捕获错误对象,并保存在状态中

	fetch( url ).then( result => console.log( result ) ).catch(e => this.setState({error : e}))

3、当错误发生时,可以在render()方法中获取到state中的错误对象,并利用条件渲染显示错误信息

	if (error) { return <p>Something went wrong.</p> }

猜你喜欢

转载自blog.csdn.net/sjs1995/article/details/107949344