我有一个简单的组件,它充当我的 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 许可协议
没有与
componentDidCatch
等效的 React 钩子。但是,React 团队计划很快添加一个。
React 文档状态:
阅读更多: https ://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes