javascript - getDerivedStateFromError 和 componentDidCatch 之间有什么区别

标签 javascript reactjs

我从here中了解到的内容:

componentDidCatch:

  • 始终在浏览器中调用
  • 在 DOM 已更新的“提交阶段”调用
  • 应该用于诸如错误报告之类的事情

getDerivedStateFromError:

  • 也在服务器端渲染期间调用
  • 当 DOM 尚未更新时在“渲染阶段”调用
  • 应用于渲染后备 UI

不过,我对有些事情还是有点困惑:

  1. 它们都捕获相同类型的错误吗?或每个生命周期 会捕获不同的错误吗?
  2. 我应该始终使用两者(可能在同一个“错误捕获”组件中)吗?
  3. “使用 componentDidCatch 进行错误恢复并不是最佳选择,因为它会强制后备 UI 始终同步渲染”这有什么问题吗?

最佳答案

问题中的陈述大部分是正确的。目前 SSR 不支持错误边界,getDerivedStateFromErrorcomponentDidCatch 不影响服务器端。

are they both catching the same type of errors? or each lifecycle will catch the different error?

他们在不同的阶段捕获相同的错误。以前,仅使用 componentDidCatch 就可以实现这一点:

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch() {
    this.setState({ hasError: true });
  }

做同样的事情,在 ReactDOMServer 中添加对异步渲染的支持之前,componentDidCatch 不可能在服务器端得到支持。

should I always use both (in the same "error-catching" component possibly)?

可以两者都使用。来自 the documentation 的示例表明:

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logComponentStackToMyService(info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

在这种情况下,他们之间的责任是分开的。 getDerivedStateFromError 只做它唯一有用的事情,即如果发生错误则更新状态,而 componentDidCatch 提供副作用并可以访问 this 组件如果需要的话实例。

"using componentDidCatch for error recovery is not optimal because it forces the fallback UI to always render synchronously" what's wrong with that?

新的 React 版本旨在提高效率的异步渲染。正如 the comment 中也提到的那样,同步渲染对于后备 UI 来说并不是一个大问题,因为它可以被视为边缘情况。

关于javascript - getDerivedStateFromError 和 componentDidCatch 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52962851/

相关文章:

javascript - 如何使用 jquery 突出显示选定的列表项?

javascript - 获取用于在页面上加载 div 的 URI?

javascript - 有没有办法使用 onclick 方法填充多个字段

javascript - 如何将 CSS 类/样式设置为 GridX 中的特定列?

reactjs - 停止 setInterval 如果在 React Native 函数中不起作用

javascript - html 和 php 文件返回空

reactjs - this.setState() 在 componentWillReceiveProps 中不起作用

reactjs - 如何将值从渲染器传递给弹出窗口

React Native 上的 Firebase 客户端

reactjs - 如何为 reactjs 中的所有子页面创建通用页眉和页脚?