根据TypeScript definition,类型为any
,而相关方法componentDidCatch()收到类型为Error
的错误。为什么会出现这种不一致?
答案 0 :(得分:3)
Typescript具有一个全局Error
界面,您可以使用。
interface Error {
stack?: string;
}
因此您可以使用
static getDerivedStateFromError(error: Error) {
// ...
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// ...
}
GetDerivedStateFromError
类型如下所示,我认为它的错误类型不应该是any
类型,而应该是Error
类型
type GetDerivedStateFromError<P, S> =
/**
* This lifecycle is invoked after an error has been thrown by a descendant component.
* It receives the error that was thrown as a parameter and should return a value to update state.
*
* Note: its presence prevents any of the deprecated lifecycle methods from being invoked
*/
(error: any) => Partial<S> | null;