根据新的react 16 release doc,它说
"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'));
发布于 2017-10-23 20:20:48
您正在捕获错误,并且catch的返回是一个承诺,因此您不会再有错误,如果您在componentDidMount中删除fetch时的.catch,这应该可以工作!
https://stackoverflow.com/questions/46888714
复制相似问题