这是我目前关于如何ErrorBoundary
在 Typescript 中正确键入 React 类组件的尝试:
import React from "react";
import ErrorPage from "./ErrorPage";
import type { Store } from "redux"; // I'M PASSING THE REDUX STORE AS A CUSTOM PROP
interface Props {
store: Store // THIS IS A CUSTOM PROP THAT I'M PASSING
}
interface State { // IS THIS THE CORRECT TYPE FOR THE state ?
hasError: boolean
}
class ErrorBoundary extends React.Component<Props,State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo: React.ErrorInfo): void {
// You can also log the error to an error reporting service
// logErrorToMyService(error, errorInfo);
console.log("error: " + error);
console.log("errorInfo: " + JSON.stringify(errorInfo));
console.log("componentStack: " + errorInfo.componentStack);
}
render(): React.ReactNode {
if (this.state.hasError) {
// You can render any custom fallback UI
return(
<ErrorPage
message={"Something went wrong..."}
/>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
这个问题是关于这个ErrorBoundary
类组件的类型。我将它分成几部分以使其更容易。
A 部分:道具和状态的类型
我做的对吗?
interface Props {
store: Store // THIS IS A CUSTOM PROP THAT I'M PASSING
}
interface State { // IS THIS THE CORRECT TYPE FOR THE state ?
hasError: boolean
}
class ErrorBoundary extends React.Component<Props,State> {}
B 部分:getDerivedStateFromError(错误)
error
我应该为参数选择什么类型?返回类型应该是State
类型吧?
static getDerivedStateFromError(error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
C部分:componentDidCatch(错误,errorInfo:React.React.ErrorInfo)
error
我应该为参数选择什么类型?对于errorInfo
,React 确实有一个ErrorInfo
看起来是正确的类型。是吗?返回类型应该是void
,对吗?
componentDidCatch(error, errorInfo: React.ErrorInfo): void {
console.log("error: " + error);
console.log("errorInfo: " + JSON.stringify(errorInfo));
console.log("componentStack: " + errorInfo.componentStack);
}
D 部分:render() 方法
返回类型应该是ReactNode
?
render(): React.ReactNode {
if (this.state.hasError) {
// You can render any custom fallback UI
return(
<ErrorPage
message={"Something went wrong..."}
/>
);
}
return this.props.children;
}