首页 > 解决方案 > 使用静态错误函数将类组件转换为功能组件

问题描述

我正在升级旧的 react pp 以使用功能组件。我遇到了错误边界类组件的问题。我根本不明白如何更新static getDerivedStateFromError更新此函数的正确语法是什么?

初始组件

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

  static getDerivedStateFromError(_error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    sendError("ErrorBoundary", { info }, error);
  }

  render() {
    if (this.state.hasError) {
      return <ErrorText />;
    } else {
      return this.props.children;
    }
  }
}

新组件,它肯定会产生某些东西,因为它永远不会将错误设置为 true,这是由静态函数完成的。

const ErrorBoundary = (props) => {
  const [hasError, setHasError] = useState(false)
  try {
    if (hasError) {
      return <ErrorText />;
    } else {
      return props.children;
    }
  } catch {
    sendError("ErrorBoundary", { info }, error);
  }
}

标签: reactjs

解决方案


现在没有办法做componentDidCatch也没有getDerivedStateFromError钩子。这是文档:

https://reactjs.org/docs/hooks-faq.html#from-classes-to-hooks

getSnapshotBeforeUpdate、componentDidCatch 和 getDerivedStateFromError:这些方法还没有 Hook 等效项,但很快就会添加。


推荐阅读