SUNYIMIN / react-review

react
2 stars 0 forks source link

在 React v16 中的错误边界是什么? #17

Open SUNYIMIN opened 4 years ago

SUNYIMIN commented 4 years ago

官方定义:如果一个 class 组件中定义了 static getDerivedStateFromError() 或 componentDidCatch() 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。当抛出错误后,请使用 static getDerivedStateFromError() 渲染备用 UI ,使用 componentDidCatch() 打印错误信息

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

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误日志上报给服务器
    logErrorToMyService(error, errorInfo);
  }

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

    return this.props.children; 
  }
}
SUNYIMIN commented 4 years ago

注意:错误边界无法捕获以下场景中产生的错误; 事件处理(了解更多) 事件处理发生的错误,不在渲染期间产生,此时,react已经知道需要展示什么内容,因而不需要在事件处理中去捕获错误,事件处理通过try catch捕获 异步代码(例如 setTimeout 或 requestAnimationFrame 回调函数) 服务端渲染 它自身抛出来的错误(并非它的子组件)