[英]React 16 Error Boundary component (using componentDidCatch) shows uncaught error
I started an app using create-react-app , and I have this Error Boundary component:我使用create-react-app启动了一个应用程序,我有这个错误边界组件:
import React from 'react'
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
console.log('shouldnt I see this logged??')
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
and I use it in this App component:我在这个 App 组件中使用它:
import React from 'react'
import ErrorBoundary from './ErrorBoundary'
class App extends React.Component {
render() {
return (
<ErrorBoundary>
<div>
<button onClick={() => { throw new Error('lets throw an error') }}>
Click to throw error
</button>
</div>
</ErrorBoundary>
);
}
}
export default App;
I am expecting that if I click the button in App
, the thrown error should be caught and I should see this logged from ErrorBoundary
: "shouldnt I see this logged??".我期待如果我点击App
的按钮,抛出的错误应该被捕获,我应该看到这个从ErrorBoundary
记录的:“我应该看到这个记录吗??”。 But I don't see that logged and it breaks the app:但是我没有看到记录并且它破坏了应用程序:
Am I misunderstanding something?我误解了什么吗?
The reason why nothing happens is that this is an error in an event handler, and these aren't caught by error boundaries.什么都没有发生的原因是这是事件处理程序中的错误,并且这些没有被错误边界捕获。 The error-handling blog post clarifies which errors are caught: 错误处理博客文章阐明了捕获的错误:
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.错误边界在渲染过程中、生命周期方法中以及在它们下面的整个树的构造函数中捕获错误。
Without error boundaries, those errors would be very tricky to catch (and in React 16, even lifecycle-method errors will make your entire app rendering disappear.)如果没有错误边界,这些错误将非常难以捕捉(在 React 16 中,即使是生命周期方法错误也会使您的整个应用程序渲染消失。)
EDIT: The actual docs are even more clear about which errors are caught.编辑: 实际文档更清楚地说明了哪些错误被捕获。 Also note that create-react-app
uses the react-error-overlay
package, which on dev-server builds replaces the entire rendering with an error screen after a brief moment.另请注意, create-react-app
使用react-error-overlay
包,在开发服务器构建中,它会在片刻之后用错误屏幕替换整个渲染。 To better see your errors getting caught, you can run a production build.为了更好地看到您的错误被捕获,您可以运行生产构建。
Error boundaries do not catch errors for:错误边界不会捕获以下错误:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.