React Error boundary

Error trapping

The error boundary is a React component that catches and prints JavaScript errors that occur anywhere in its child tree, and instead of rendering the broken child tree, it renders the alternate UI.

In simple terms, this is a component that renders the standby UI when a child component fails.

Only class components can be error bound components.

In most cases, you only need to declare one error bound component and use it throughout the application. The granularity of error boundaries depends on requirements. According to the understanding, for example, there is a classic left and right layout, left navigation bar, right interior bar; Content should be wrapped in an error bound component so that when content crashes, it does not affect the navigation bar.

usage

You can define a common component that wraps child components where needed.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so that the next rendering can display the degraded UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Catch an error message
    // You can also report error logs to the server
    logErrorToMyService(error, errorInfo);
  }

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

    // Render the correct view
    return this.props.children; }}Copy the code

Used in a component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
Copy the code

other

Balabala document:

Note that error bounds do not catch errors in scenarios where event handling (for more on this) asynchronous code (such as setTimeout or requestAnimationFrame callback functions) the server renders errors thrown by itself (not by its children)

Errors in asynchronous code and events can be handled by trying {} catch(e) {} :

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      hasError: false
    };
  }
  
  onClick(e) {
    tru {
      // TODO
    } catch(err) {
      this.setState({ hasError: true}}})render() {
    const { hasError } = this.state;
    if (hasError) {
      return <h1>Caught an error.</h1>
    }
    return <button onClick={this.handleClick}>Click Me</button>}}Copy the code

The End. Reference Zh-hans.reactjs.org/docs/error-…