您当前的位置: 首页 > 

【03】

暂无认证

  • 1浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

react错误边界处理

【03】 发布时间:2021-02-04 19:33:38 ,浏览量:1

错误边界

当一个页面包含N个组件时,其中一个组件报错,就会导致整个页面白屏,这并不是我们想要的

ErrorPage.jsx

import React, {Component} from 'react';
import ErrorView from "./ErrorView";
class ErrorPage extends Component {
    render() {
        return (
            
                零零三
                
            
        );
    }
}
export default ErrorPage;

ErrorView.jsx

import React, {Component} from 'react';

class ErrorView extends Component {
    state={
        list: null
    }
    render() {
        const {list} = this.state
        return (
            
                {list.map((item, index)=>{
                    return index={index}
                })}
            
        );
    }
}

export default ErrorView;

错误页面的结果为

整个页面都是白屏

进行错误边界的处理

ErrorBoundary.jsx

import React, {Component} from 'react';

class ErrorBoundary extends Component {
    state = {
        hasError: false,
        error: null,
        errorInfo: null
    }
    componentDidCatch(error, errorInfo) {
        this.setState({
            hasError: true,
            error,
            errorInfo
        })
    }

    render() {
        if (this.state.hasError){
            return {this.props.render(this.state.error,this.state.errorInfo)}
        }
        return this.props.children;
    }
}
export default ErrorBoundary;

ErrorView.jsx

import React, {Component} from 'react';

class ErrorView extends Component {
    state={
        list: null
    }
    render() {
        const {list} = this.state
        return (
            
                {list.map((item, index)=>{
                    return index={index}
                })}
            
        );
    }
}

export default ErrorView;

ErrorPage.jsx

import React, {Component} from 'react';
import ErrorView from "./ErrorView";
import ErrorBoundary from './ErrorBoundary'
class ErrorPage extends Component {
    render() {
        return (
            
                零零三
                组件发生了错误/error:{error.message}}>
                    
                

            
        );
    }
}
export default ErrorPage;

结果

关掉错误弹窗

这样只会将发生该错误的组件展示错误信息,而不是整个页面白屏

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0397s