小编典典

getDerivedStateFromError和componentDidCatch有什么区别

reactjs

我从这里了解到:

componentDidCatch

  • 总是在浏览器中被调用
  • 在DOM已更新的“提交阶段”期间调用
  • 应该用于错误报告之类的东西

getDerivedStateFromError

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

不过,我还是有些困惑:

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

阅读 477

收藏
2020-07-22

共1个答案

小编典典

问题中的陈述大部分是正确的。当前,SSR不支持错误边界,getDerivedStateFromError并且componentDidCatch不会影响服务器端。

他们都捕获相同类型的错误吗?还是每个生命周期都会捕获不同的错误?

他们正在捕获相同的错误,但是处于不同的阶段。以前这可能是componentDidCatch单独使用的:

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

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

做同样的事情,componentDidCatch直到将对异步渲染的支持添加到服务器端之前,它没有机会在服务器端得到支持ReactDOMServer

我应该总是同时使用两者吗(可能在同一个“捕捉错误”组件中使用)?

可以同时 使用。文档中的示例显示:

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在需要时访问组件实例。

“使用componentDidCatch进行错误恢复不是最佳选择,因为它强制后备UI始终同步呈现”这有什么问题?

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

2020-07-22