react 错误边界
In this article, you’ll learn about Error Boundaries via code snippets and interactive demos. If you’re still wondering what Error Boundaries are and how they work, this simple guide is for you!
在本文中,您将通过代码片段和交互式演示来了解错误边界 。 如果您仍然想知道什么是错误边界以及它们如何工作,那么本简单指南非常适合您!
Error Boundaries were introduced in React v16 as a way to catch tricky errors that occur during the render phase. In the past this would have caused the app to unmount completely, and the user would just see a blank web page, which is not ideal!
在React v16中引入了错误边界,以捕获在渲染阶段发生的棘手错误。 在过去,这会导致应用程序完全卸载,而用户只会看到空白网页,这是不理想的!
It’s inevitable that we’ll encounter unexpected errors in our apps. You could be trying to access a deeply-nested property on an object that doesn’t exist, or sometimes it’s not in your control (like a failed HTTP request to a 3rd-party API).
不可避免的是,我们会在应用程序中遇到意外错误。 您可能试图访问一个不存在的对象上的深层属性,或者有时不在您的控件中(例如,对第三方API的HTTP请求失败)。
In the demo below, we’ll simulate an error to see what normally happens without an Error Boundary.
在下面的演示中,我们将模拟一个错误,以查看没有错误边界的情况下通常会发生什么。
Click the “+” button, and it will fail at 5:
单击“ +”按钮,它将在5失败:
See the Pen alligatorio-react-error-boundaries-1 by wle8300 (@wle8300) on CodePen.
请参阅CodePen上wle8300 ( @ wle8300 )的Pen alligatorioio-react-error-boundaries-1 。
class BuggyCounter extends Component {
state = {
counter: 0
};
handleClick = () => {
this.setState({
counter: this.state.counter + 1
});
}
render() {
if (this.state.counter === 5) {
// Simulate an error!
throw new Error('I crashed!');
}
return (
{this.state.counter}
);
}
};
When the app encounters an error, the component completely unmounts itself and the user is left with a blank HTML page . This can obviously leave users feeling confused, and they won’t know what to do next.
当应用遇到错误时,该组件将完全卸载,而用户将看到空白HTML页面。 这显然会使用户感到困惑,并且他们不知道下一步该怎么做。
Error Boundaries provides a way to gracefully handle these errors!
错误边界提供了一种优雅处理这些错误的方法!
What are Error Boundaries exactly? Contrary to what you may think, it’s not a new component or JavaScript library. It’s more like a strategy for handling errors in React components.
确切的错误边界是什么? 与您可能想到的相反,它不是新组件或JavaScript库。 它更像是一种用于处理React组件中的错误的策略。
Specifically, it’s the usage of 2 methods that are available in React components:
具体来说,它是React组件中提供的2种方法的用法:
class MyErrorBoundary extends Component {
state = {
error: null
}
static getDerivedStateFromError(error) {
// Update state so next render shows fallback UI.
return { error: error };
}
componentDidCatch(error, info) {
// Log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.error) {
// You can render any custom fallback UI
return Something broke
;
}
return this.props.children;
}
};
static getDerivedStateFromError
is a lifecycle method that allows the Error Boundary a chance to update the state and thus triggering a last render(). In the above code snippet, the state is used to reveal a human-friendly error message instead of the broken component (eg.: this.props.children
).
static getDerivedStateFromError
是一种生命周期方法,它使Error Boundary有机会更新状态并因此触发最后的render() 。 在上面的代码片段中,状态用于显示人类友好的错误消息,而不是损坏的组件(例如: this.props.children
)。
componentDidCatch
is a lifecycle method designed for triggering side-effects (eg.: logging the error to tools like Crashlytics). You can access info.componentStack to get a developer-friendly stack trace that will be useful for triaging the bug.
componentDidCatch
是一种生命周期方法,旨在触发副作用(例如:将错误记录到Crashlytics之类的工具中)。 您可以访问info.componentStack以获得对开发人员友好的堆栈跟踪,这将有助于对该错误进行分类。
So what is an Error Boundary? Any React Component is considered an Error Boundary when it employs at least one of these lifecycle methods.
那么什么是错误边界? 当任何React组件采用至少一种生命周期方法时,将被视为错误边界。
Good practices suggest that you’ll want to create a component that’s purpose-built as an Error Boundary instead of mixing error-handling logic into your generic components.
良好做法建议您创建一个专门构建为错误边界的组件,而不是将错误处理逻辑混入您的通用组件中。
Let’s slightly modify
, and then wrap it around
so it’ll catch the error!
让我们稍微修改
,然后将其包装在
周围,以捕获错误!
class MyErrorBoundary extends Component {
state = {
errorMessage: ''
}
static getDerivedStateFromError(error) {
return {errorMessage: error.toString()}
}
componentDidCatch(error, info) {
this.logErrorToServices(error.toString(), info.componentStack)
}
// A fake logging service
logErrorToServices = console.log
render() {
if (this.state.errorMessage) {
return (
{this.state.errorMessage}
)
}
return this.props.children
}
}
class BuggyCounter extends Component {
// nothing was modified :P
}
function App() {
refreshPage = () => history.go(0)
return (
);
}
Try clicking the “+” button again. Once it reaches 5, it will crash gracefully. Additionally, you can open your console to view a stack trace!
尝试再次单击“ +”按钮。 一旦达到5,它将正常崩溃。 此外,您可以打开控制台以查看堆栈跟踪!
See the Pen alligatorio-react-error-boundaries-2 by wle8300 (@wle8300) on CodePen.
请参阅CodePen上wle8300 ( @ wle8300 )的Pen alligatoratorio-react-error-boundaries-2 。
Instead of completed crashing, we can use Error Boundaries to substitute a fallback UI. This provides visual feedback to the user that something broke, while allowing them to continue interacting with our app.
我们可以使用错误边界代替后备UI,而不是完全崩溃。 这样可以向用户提供视觉反馈,说明出现了问题,同时允许他们继续与我们的应用进行交互。
They can choose to navigate away, or even reach out to customer service to help resolve their situation! It’s a great way to redeem an otherwise unfortunate user experience.
他们可以选择离开,甚至可以联系客户服务来解决他们的情况! 这是赎回原本不幸的用户体验的好方法。
Error Boundaries are only available in Class-based React Components. At the time of this writing, there isn’t a way to implement it using React Hooks yet.
错误边界仅在基于类的React组件中可用。 在撰写本文时,还没有使用React Hooks来实现它的方法。
Error Boundaries actually aren’t in direct competition with try…catch statements. Error Boundaries are only designed for intercepting errors that originate from 3 places in a React component:
错误边界实际上并不与try ... catch语句直接竞争。 错误边界仅用于拦截来自React组件中3个地方的错误:
During render phase
在渲染阶段
In the constructor
在构造函数中
Basically… the React-y parts of a component. As a counterpoint, these are the places where Error Boundaries won’t be able to catch an error:
基本上是……组件的React-y部分。 作为对策,这些是错误边界将无法捕获错误的地方:
Event handlers (eg., onClick
, onChange
, etc.)
事件处理程序(例如onClick
, onChange
等)
setTimeout or requestAnimationFramecallbacks
setTimeout或requestAnimationFramecallbacks
So Error Boundaries don’t really impact how you use try…catch. They’re both needed as a robust strategy for handling errors in React ⚔
因此,错误边界不会真正影响您使用try ... catch的方式 。 它们都是处理React errors中错误的可靠策略。
Now that Error Boundaries are available since React v16, it’s generally advisable to use at least 1 Error Boundary at the root of your app (eg., the App.js file). This will prevent users from seeing a blank HTML page, and perhaps see a nice fallback UI instead.
既然从React v16开始可以使用错误边界,通常建议在应用程序的根目录(例如App.js文件)至少使用1个错误边界。 这将防止用户看到空白HTML页面,并且可能会看到一个不错的后备UI。
If you want to go the extra mile you can employ several different kinds of Error Boundaries that employ different fallback UIs, or those that only log errors to a 3rd-party service.
如果您想加倍努力,可以使用几种不同类型的错误边界,这些错误边界采用不同的后备UI,或者仅将错误记录到第三方服务的UI。
Check out the official React docs for more info!
查看官方的React文档以获取更多信息!
翻译自: https://www.digitalocean.com/community/tutorials/react-error-boundaries
react 错误边界