反应钩子相当于componentDidCatch?

新手上路,请多包涵

我有一个简单的组件,它充当我的 React 应用程序中的错误边界,并将任何错误传递给日志服务。

它看起来像这样:

 export class CatchError extends React.PureComponent {
  state = {
    hasError: false
  }

  componentDidCatch(error, info) {
    this.props.log({ error, info })
    this.setState({ hasError: true })
  }

  render() {
    const child = typeof this.props.children === "function"
      ? this.props.children({ error: hasError })
      : children

    return React.cloneElement(child, { error: this.state.hasError })
  }
}

是否有一个相当于 componentDidCatch 的 React 钩子,所以我可以让这个组件成为一个函数而不是一个类?

所以它可能看起来像这样:

 export function CatchError({ children, log }) {
  const [hasError, setHasError] = useState(false)
  const caught = useDidCatch()

  useEffect(() => {
    const [error, info] = caught
    log({ error, info })
    setHasError(true)
  }, [caught])

  const child = typeof children === "function"
    ? children({ error: hasError })
    : children

  return React.cloneElement(child, { error: hasError })
}

原文由 sdgluck 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

没有与 componentDidCatch 等效的 React 钩子。

但是,React 团队计划很快添加一个。

React 文档状态:

目前还没有不常见的 getSnapshotBeforeUpdate 和 componentDidCatch 生命周期的 Hook 等价物,但我们计划很快添加它们。

阅读更多: https ://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes

原文由 sdgluck 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进