React捕获错误 UI降级处理

554 阅读1分钟

自定义一个捕获错误的父组件,把子组件包裹起来

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

方法一
  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }
方法二
  componentDidCatch(error, errorInfo) {
    //
    this.setState({
    	hasError: true
    })
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

食用方式

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>