React error boundary

Time:2021-5-12

What is the wrong boundary

Error bounds are a special component that can be used to capture and print errors that occur in theIts subcomponents are located anywhere in the treeJavaScript error, and render the alternate UI.
The wrong boundary will beDuring renderingDeclaration cycle methodAnd the whole component treeConstructorsError caught in. So the error boundary cannot capture the errors generated in the following scenarios:

  • event processing
  • Asynchronous code
  • Server rendering
  • Mistakes thrown by oneself

Error bounds are similar to JavaScript’s catch, but only for react

Why use the wrong boundary

Error bounds can solve the problem that JavaScript errors in some UI will cause the whole application to crash.
Since react 16, any error not caught by the error boundary will cause the whole react component tree to be unloaded. Using the error boundary can provide a better user experience

How do you use it?

Basic usage

Defined in class componentstatic getDerivedStateFromError()orcomponentDidCatch()With either (or both) of the two declaration cycle methods, the component becomes an error boundary.

  • getDerivedStateFromError()Used to handle errors
  • usecomponentDidCatch()To output a complete error message
//Definition
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {    
      //Update the state to display the degraded UI in the next rendering    
      return { hasError: true };  
  }  
  componentDidCatch(error, errorInfo) {   
      //You can also report the error log to the server    
      logErrorToMyService(error, errorInfo); 
  }
  render() {   
      if (this.state.hasError) {      
          //You can customize the degraded UI and render it      
          return <h1>Something went wrong.</h1>;   
      }
    return this.props.children; 
  }
}
//Use
<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

The error boundary can be combined with error monitoring to record the errors generated by the production environment

When and where to use it

Wrap the wrong boundary outside any react component to protect the content outside the boundary from crashing

Related knowledge

  • In the development environment, react16 will print all errors occurred during rendering to the console, and also provides component stack tracking

React error boundary

  • try/catch

try  /  catch   It can only be used for imperative code, but the react component is declarative, so error bounds are needed to catch errors