美文网首页
React错误边界

React错误边界

作者: peroLuo | 来源:发表于2019-12-19 21:01 被阅读0次
  1. getDerivedStateFromError
  2. componentDidCatch
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; 
  }
}

相关文章

网友评论

      本文标题:React错误边界

      本文链接:https://www.haomeiwen.com/subject/typvnctx.html