reactjs - 使用静态错误函数将类组件转换为功能组件
问题描述
我正在升级旧的 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);
}
}
解决方案
现在没有办法做componentDidCatch
也没有getDerivedStateFromError
钩子。这是文档:
https://reactjs.org/docs/hooks-faq.html#from-classes-to-hooks
getSnapshotBeforeUpdate、componentDidCatch 和 getDerivedStateFromError:这些方法还没有 Hook 等效项,但很快就会添加。
推荐阅读
- python - 获取具有条件的数据框的下一行
- docker - 使用 Cloudflare 设置 Traefik
- jquery - 无法读取未定义的 toArrays 的属性
- c# - 我正在尝试对列表中的数组元素(字符串)进行线性搜索,但我遇到了问题
- python-3.x - 如何提取隐藏的li文本
- excel - 从 VBA 调用时 PowerShell 命令不起作用,但在其他情况下有效
- python-3.x - 根据键值合并字典列表
- android - FCM 代币发行
- c# - 如何在 node.js 或 C#/.NET 中发送消息处理通知电子邮件?
- javascript - 从表格中出来的附加 div