React将类组件转换为带有静态错误函数的功能组件



我正在升级旧的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);
}
}

现在没有办法在钩子上做componentDidCatchgetDerivedStateFromError。下面是文档:

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

getSnapshotBeforeUpdate, componentDidCatch和getDerivedStateFromError:目前还没有这些方法的钩子等效,但它们将很快被添加。

最新更新