这是我目前尝试如何在Typescript中正确编写React ErrorBoundary
类组件的方法:
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
类组件的类型。我将其分成几部分以使其更易于理解。
第一部分:props和state的类型
我的做法正确吗?
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> {}
第二部分:getDerivedStateFromError(error)
在error
参数中,我应该选择哪种类型?返回类型应该是State
类型,对吗?
static getDerivedStateFromError(error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
第三部分:componentDidCatch(error, 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;
}
import type
语法是在较新版本的Typescript中发布的,不确定是哪个版本,但在一些旧版本中无法使用。 - cbdeveloperErrorBoundary
。但我猜我可以通过react-redux
中的useStore()
访问存储,因为ErrorBoundary
将在<Provider store={store}>
内部。谢谢。编辑:实际上我不能在类组件中使用useStore
。刚发现了那个错误信息:React Hook“useStore”不能在类组件中调用。React Hooks必须在React函数组件或自定义React Hook函数中调用。 - cbdeveloper