根据新的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'));