React 最佳实践中的错误处理 [英] Error handling in React best practices

查看:41
本文介绍了React 最佳实践中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 React 中渲染一个组件(具有许多子组件)并且由于某种原因抛出 JS 错误时,处理这个问题的最佳方法是什么?当然我可以捕捉到错误,但最终你想要呈现的东西可能无法捕捉,因为缺少需要的信息.您可以使用 propTypes 中的 .isRequired 提前进行验证,但这只是在失败时控制台发出警告.

When rendering a component in React (with many subcomponents) and a JS error is thrown for whatever reason, what's the best way to handle this? Sure I can catch the error but ultimately the thing you want to render may not be able to because require information is missing. You can validate ahead of time with .isRequired in the propTypes but that just console's a warning when it fails.

推荐答案

React 16 引入了一个名为 错误边界" 的新概念来处理 React 组件内部发生的错误,而不会破坏整个应用程序.

React 16 introduces a new concept called "error boundary" to handle errors occur inside React components without breaking the whole app.

><块引用>

错误边界是捕捉 JavaScript 错误的 React 组件在其子组件树中的任何位置,记录这些错误并显示后备 UI 而不是崩溃的组件树.

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

使用新的生命周期方法 componentDidCatch(error, info) 使错误边界组件成为可能.与其他生命周期方法不同,只有在渲染期间、生命周期方法或组件的任何子(包括所有孙子)组件的构造函数中发生任何错误时,才会调用此方法.

Error Boundary components have been made possible with a new life cycle method componentDidCatch(error, info). Not like other life cycle methods, this will get called only if any error occurred in during rendering, in lifecycle methods, or constructors of any child (including all grandchildren) component of the component.

在代码中,错误边界组件将如下所示.

In code, Error Boundary component will be something like follows.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Error occurred!</h1>;
    }
    return this.props.children;
  }
}

我们可以在代码中将此错误边界组件用作普通组件.

We can use this Error Boundary component as a normal component in our code.

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

现在,如果 MyComponent 在渲染、生命周期方法或构造过程中抛出任何 JavaScript 错误,错误边界组件的 componentDidCatch 将触发并更改状态以显示 Error 发生! 消息而不是损坏的 MyComponent.

Now if MyComponent throws any JavaScript error in during rendering, in lifecycle method, or in constructing, componentDidCatch of Error Boundary component will trigger and change the state to show Error occurred! message instead of the broken MyComponent.

在迁移到 React 16 之前,您想了解这个新功能的另一个重要含义.以前,如果发生错误,它会留下损坏的 UI,即使它通常不会按预期工作,直到您重新加载页面.但是,在 React 16 中,如果错误没有被任何错误边界处理,则会导致整个应用程序卸载.

This new functionality comes with another vital implication that you wanted to know before migrating to React 16. Previously, if an error occurs, it leaves corrupted UI even though it doesn't usually work as expected until you reload the page. However, in React 16, if an error hasn't handled by any error boundary, it will result in unmounting of the whole app.

因此,您可以适当地向应用添加错误边界,这将为您的用户提供更好的体验.因此,即使用户界面的某些区域崩溃了,用户也可以与您应用的一部分进行交互.

Because of this, you are adding error boundaries to your app appropriately will give a better experience to your user. So users will be able to interact with a part of your app even though some areas of UI have crashed.

参考关于错误边界的React官方文档这篇官方博文 了解更多信息.它们涵盖了您需要了解的有关此新功能的几乎所有内容.

Refer React official documentation on error boundaries or this official blog post for more information. They cover almost everything you need to know about this new feature.

这篇关于React 最佳实践中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆