这是我目前在如何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(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;
}
您将获得该文件中所有的答案index.d.ts
从@types/react
。如果使用的是类似VSCode的IDE,则可以按住Ctrl键并单击某个类型以直接转到其定义。
这是对您问题的精确答案,但是在此之前,让我建议您更喜欢使用reacthooks
而不是class。
OP的编辑:我从不使用类组件,总是喜欢使用函数和钩子,但是从React docs上的Error Boundaries出发:
错误边界的工作方式类似于JavaScript catch {}块,但对于组件而言。只有类组件才能成为错误边界。
我给出的内容是index.d.ts
16.9.49版中的内容。
A部分:是的,就是这样。
B部分:如您在658行所见error
,类型为any
,返回类型为state
或的一部分null
。
C部分:在第641行,您将看到error是类型,Error
而return类型是void
。
D部分:在494行,您可以看到render应该返回一个ReactNode
…
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句