0

根据新的React 16 发布文档,它说

“React 16 将渲染过程中发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。”

我有一个组件和一个组件。我在 then 承诺块中触发了一个错误。但它会调用 promise 的 catch 方法,不会调用父组件的 componentDidCatch。我不确定这是否是预期的行为。

这是jsfiddle https://jsfiddle.net/john1jan/Luktwrdm/14/

class Parent extends React.Component {  
  constructor(props){
    super(props);
    this.state={hasError:false}
  }

  render() {
    if(this.state.hasError){
      return <div>Something went wrong</div>
    }

    return (
      <div>
        <h1>I am parent</h1>
        <Child></Child>
      </div>
    );
  }
  componentDidCatch(error,errorInfo){
    this.setState({
      hasError:true
    })
  }
}

class Child extends React.Component {

  render() {
    return (
      <div>
        <h1>I am child</h1>
      </div>
    );
  }

  componentDidMount(){
    fetch("https://jsonplaceholder.typicode.com/posts").then((response) => {
      throw new Error("I am the error in promise");
    }).catch((error)=>{
      console.log("Error caught in catch",error);
    })
    ;
  }
}

ReactDOM.render(<Parent name="world"/>, 
document.getElementById('container'));
4

2 回答 2

5

只是想向任何进入这个问题寻找答案的人指出。

React 16 将渲染过程中发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。

componentDidCatch只会在渲染生命周期方法中触发。

由于您的错误是在promise中抛出的。它是异步的,不会成为渲染生命周期的一部分,因此您需要自己处理错误。

于 2018-04-04T17:09:28.967 回答
1

您正在捕获错误,并且 catch 的返回是一个承诺,因此您不再有错误,如果您在 componentDidMount 中删除 .catch ,这应该可以工作!

于 2017-10-23T12:20:47.747 回答