我正在更新一个旧的 React 应用程序并将数百个旧组件转换为新组件。我用 static
函数和 componentDidCatch
遇到了障碍,我知道它不再有钩子了。如何将此类升级为函数?
原始函数
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;
}
}
}
export default ErrorBoundary;
这是我目前所拥有的
const ErrorBoundary = (props) => {
const [error, hasError] = useState(false)
// code is unreachable
ErrorBoundary.getDerivedStateFromError = (_error) => {
hasError(true)
return error;
}
// cant use this lifecycle piece
componentDidCatch(error, info) {
sendError("ErrorBoundary", { info }, error);
}
if (error) {
return <ErrorText />;
} else {
return props.children;
}
}