what's the difference between getDerivedStateFromError and componentDidCatch

前端 未结 3 866
情深已故
情深已故 2020-12-14 14:31

What I understood from here:

componentDidCatch:

  • is called always in the browser
  • is called during the \"commit phase\" when the DO
3条回答
  •  一整个雨季
    2020-12-14 15:05

    The statements in the question are mostly correct. Currently error boundaries aren't supported in SSR, getDerivedStateFromError and componentDidCatch don't affect server side.

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

    They are catching same errors but at different phases. This previously was possible with componentDidCatch alone:

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

    and

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

    do the same thing, componentDidCatch has no chances to be supported on server side until the support for asynchronous rendering will be added to ReactDOMServer.

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

    You can use both. An example from the documentation shows that:

    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 

    Something went wrong.

    ; } return this.props.children; } }

    In this case responsibilities are divided between them. getDerivedStateFromError does the only thing it is good for, i.e. updates the state if an error occurs, while componentDidCatch provides side effects and can access this component instance if needed.

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

    New React releases are aimed at asynchronous rendering which is more efficient. As it was also mentioned in the comment, synchronous rendering is not a big concern for fallback UI because it can be considered edge case.

提交回复
热议问题