在我的 componentDidCatch() 方法中捕获错误,并呈现自定义错误 UI。
什么是从错误中继续前进而不是让用户强制更新页面的巧妙方法?
import * as React from "react";
interface ErrorBoundaryState {
hasError: boolean;
errorInfo: React.ErrorInfo;
}
export class ErrorBoundary extends React.Component<{}, ErrorBoundaryState> {
constructor(props: any) {
super(props);
this.state = {
hasError: false,
errorInfo: undefined,
};
}
public componentDidCatch(error: Error, info: React.ErrorInfo) {
this.setState({
hasError: true,
errorInfo: info
});
console.error(error, info);
}
public render() {
if (this.state.hasError) {
return (
<h2>Something went wrong, please try again later.</h2>
);
}
return this.props.children;
}
}
当 hasError 设置为 true 时,它会停留在那里。将它设置为 false 并再次向孩子们展示的好地方在哪里?