react 错误边界
If you have built a React app at any point in your programming career, you probably have experienced an error at some point that was cryptic and did not provide any meaningful context on what actually happened.
如果您在编程生涯中的任何时候都构建了一个React应用,那么您可能在某个时候遇到了一个错误,该错误是一个隐秘的,并且没有提供关于实际发生的任何有意义的上下文。
This probably means the error occured at some point in the application and our React component did not handle the error gracefully, well mostly because it was none of its business to make sure the entire app holds.
这可能意味着该错误在应用程序中的某个时刻发生,并且我们的React组件无法优雅地处理该错误,主要是因为确保整个应用程序正常运行与它无关。
引入错误边界 ( Introducing Error Boundaries )
A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for React users, React 16 introduces a new concept of an “error boundary”.
用户界面中JavaScript错误不应破坏整个应用程序。 为了为React用户解决此问题,React 16引入了“错误边界”的新概念。
An Error Boundary is a React component that catches errors within it's children and does something meaningful with them such as post them to an error logging service or display a fallback UI for the specific child while maintaining the rest of the React app's sanity.
Error Boundary是一个React组件,它可以捕获其子级中的错误并对其进行有意义的处理,例如将其发布到错误记录服务或为特定子级显示后备UI,同时保持其余的React应用程序的健全性。
Therefore, for a block of functionality to be covered by Error Boundaries, it has to be a child of one in the first place.
因此,对于要由“错误边界”覆盖的功能块,它首先必须是一个子元素。
Before we get started on an example of how you can use the React 16, beware that Error Boundaries will not catch errors in:
在我们开始使用如何使用React 16的示例之前,请注意错误边界不会捕获以下错误:
- Event handlers. ** - Use a
try / catch
block instead within event handlers. 2. Asynchronous code** 事件处理程序。 **-在事件处理程序中使用try / catch
块。 2.异步代码** - Server side rendering 服务器端渲染
- Errors within the Error Boundary Component. - You cannot save others if you cannot save yourself first. 错误边界组件内的错误。 -如果不能先保存自己,就不能保存其他人。
componentDidCatch() ( componentDidCatch() )
Lifecycle methods are special functions that are invoked at different stages in the life of a component. These stages can be categorized into Mounting, Updating, Unmounting and Error handling.
生命周期方法是在组件生命周期的不同阶段调用的特殊功能。 这些阶段可以分为安装 , 更新 , 卸载和错误处理 。
For a component to be considered an Error Boundary, it has to make use of the componentDidCatch()
lifecycle method to handle errors. It works in the same way that Javascript's try/catch
works.
对于被认为是错误边界的组件,它必须利用componentDidCatch()
生命周期方法来处理错误。 它的工作方式与Java代码的try/catch
相同。
the componentDidCatch
method is invoked with the an error
and info
parameters that contain more context on the thrown error.
使用error
和info
参数调用componentDidCatch
方法,该参数包含有关引发的错误的更多上下文。