React 16 Error Boundary组件(使用componentDidCatch)显示未捕获的错误 [英] React 16 Error Boundary component (using componentDidCatch) shows uncaught error
问题描述
我使用
我误解了吗?
什么都没发生的原因是这是事件处理程序中的错误,并且不会被错误边界捕获。 错误处理博客post 阐明捕获了哪些错误:
错误边界在渲染期间,生命周期方法以及整个构造函数中捕获错误在它们下面的树。
没有错误边界,这些错误将非常棘手(在React 16中,甚至是生命周期方法错误)将使整个应用程序呈现消失。)
编辑:实际文档更加清楚地发现了哪些错误。另请注意, create-react-app
使用 react-error-overlay
软件包,该软件包在dev-server上将替换片刻之后,整个屏幕将显示错误屏幕。为了更好地发现错误,可以运行生产版本。
I started an app using create-react-app, and I have this Error Boundary component:
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:
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??". 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.)
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. To better see your errors getting caught, you can run a production build.
这篇关于React 16 Error Boundary组件(使用componentDidCatch)显示未捕获的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!