React 错误边界的使用方法

关于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>
	)
}

此时出现错误的话则会在原本组件的位置提示:组件发生错误,
而其他组件依然能够正常运行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值