React设置错误边界后,仍然报错

题主开发了一个safeComponent组件,使用错误边界来捕获render错误,防止整个页面的crash。但是我设置static getDerivedStateFromErrorcomponentDidCatch 这两个函数后,将他应用在一个错误的组件中,还是报错。
希望有相关使用经验的大神帮帮忙~~~~

safeComponent源码

import React, {Component} from  'react'
import {View} from  'react-native'

export default class SafeComponent extends Component {
    constructor(props) {
      super(props);
      this.state = { error: null, errorInfo: null, isError:false};
    }

    static getDerivedStateFromError(error) {
        return { isError: true };
      }
    
    componentDidCatch (error) {
        this.setState({isError: true});
        console.log('get the error', error);
    }
    
    render() {
        console.log('render', this.state.isError);
      if (this.state.isError) {
        return (
          <View/>
        );
      }
      return this.props.children;
    }  
  }

errorComponent render源码

render() {
    throw new Error('baocuola!')
}

调用:

<safeComponent>
    <errorComponent/>
</safeComponent>

在rn中的报错信息:
image.png

react version 16.11.0
reactnative version 0.61.2

阅读 828
评论
    2 个回答

    我试了几次, 发现在开发模式下仍旧报错, 但是build出来后就好了.

    class One extends Component {
      state = { error: false, count: 0 };
      handler = () => this.setState(d => ({ count: d.count + 1 }));
    
      render() {
        const { count } = this.state;
        if (count > 3) {
          throw new Error('I crashed!');
        }
        return (
          <>
            <h1>One {count}</h1>
            <button onClick={this.handler}>Click</button>
          </>
        );
      }
    }
    
    class ErrorComponent extends Component {
      state = { error: false, count: 0 };
    
      static getDerivedStateFromError() {
        return { error: true };
      }
    
      componentDidCatch(err) {
        console.log(err);
      }
    
      render() {
        const { error } = this.state;
        const { children } = this.props;
        return <>{error ? <h1>Error</h1> : children}</>;
      }
    }
    
    class App extends Component {
      render() {
        return (
          <div>
            <ErrorComponent>
              <One></One>
            </ErrorComponent>
          </div>
        );
      }
    }
    
    export default App;
    
      相似问题
      推荐文章