代码之家  ›  专栏  ›  技术社区  ›  Hemadri Dasari

react中的static getDerivedStateFromError是什么[[副本]

  •  2
  • Hemadri Dasari  · 技术社区  · 7 年前

    here :

    componentDidCatch

    • 总是在浏览器中调用
    • 应该用于错误报告之类的东西

    getDerivedStateFromError

    • 在服务器端呈现期间也调用
    • 当DOM尚未更新时,在“呈现阶段”调用
    • 应用于呈现回退UI

    不过,我还是有些困惑:

    1. 我是否应该总是同时使用这两者(可能在同一个“错误捕获”组件中)?
    2. “使用componentDidCatch进行错误恢复不是最佳选择,因为它会强制回退UI始终同步呈现”
    0 回复  |  直到 6 年前
        1
  •  30
  •   Estus Flask    7 年前

    这个问题的陈述基本上是正确的。当前SSR中不支持错误边界, getDerivedStateFromError 和 componentDidCatch 不要影响服务器端。

    它们是否都捕捉到相同类型的错误?或者每个生命周期将捕获不同的错误?

    组件DIDCATCH 独自一人:

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

    和

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

    组件DIDCATCH 在将对异步呈现的支持添加到服务器端之前,没有机会在服务器端得到支持 ReactDOMServer .

    你呢 可以 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; 
      }
    }
    

    在这种情况下,责任在他们之间分配。 做唯一有用的事情,即在发生错误时更新状态,而 组件DIDCATCH this 组件实例(如果需要)。

    新的React版本旨在实现更高效的异步渲染。正如在 the comment

        2
  •  15
  •   Shubham Khatri    7 年前

    当呈现过程中、生命周期方法中或任何子组件的构造函数中出现错误时,将调用这两个方法。它们可以在实现错误边界时使用

    根据 React docs

    getDerivedStateFromError 生命周期是在子组件抛出错误后调用的。它接收作为参数抛出的错误,并应返回一个值以更新状态。


    抓住不同的错误?

    而 只接收错误作为参数,componentDidCatch还接收第二个参数 info, i.e An object with a componentStack key containing information about which component threw the error.

    getDerivedStateFromError() componentDidCatch() 相反。而 componentDidCatch 也可用于设置状态,但在将来的版本中将不推荐使用

    应该用于记录错误之类的副作用


    @Brian Vaughn 在您提供的链接中详细介绍了它们的用法

    componentDidCatch是提交阶段的生命周期,但没有提交 服务器上的阶段。getDerivedStateFromError是一个呈现阶段

    渲染阶段恢复更安全。 错误恢复的故事 组件DIDCATCH 组件下面的所有内容的“null”中间提交 出错了。这可能会导致任何 实现componentDidMount或 componentdiddupdate并假设它们的ref是非空的 (因为它们总是在非错误情况下)。

    getDerivedStateFromError错误 不强制同步渲染 . 因为状态从提交更新 阶段生命周期总是同步的 恢复不是最佳的,因为它强制回退UI始终 同步渲染(诚然,这不是一个大问题,因为 错误恢复应该是边缘情况。)

    如果发生错误,错误边界 getDerivedStateFromError() 方法将首先被调用(以更新 然后 (一旦将回退UI提交到 DOM)。

    componentWillUpdate,componentdiddupdate)它们也会被调用,


    “使用componentDidCatch进行错误恢复不是最佳的,因为 用这个?

    这意味着,componentDidCatch在呈现回退UI的render方法之后被调用,这可能会导致更多的问题 getDerivedStateFromError错误

        3
  •  4
  •   AmerllicA    6 年前

    事实上,他们都有相同的目标,但在不同的阶段,毫无疑问,写作 ErrorBoundary 我使用的组件 getDerivedStateFromError 因为我遵守 ReactJs Docs . 医生有这样一句话:

    getDerivedStateFromError() 在抛出错误后呈现回退UI。使用 componentDidCatch()

    当然,它有一些原因,所以呈现我经常使用的回退UI 为了获取信息和做一些我用的事情 componentDidCatch