reactjs - 我们可以在 getDerivedStateFromError() 中期待什么错误类型?
问题描述
根据TypeScript 定义,类型是any
,而相关方法componentDidCatch()接收到类型错误Error
。为什么会出现这种不一致?
解决方案
Typescript 有一个Error
可以使用的全局接口。
interface Error {
stack?: string;
}
所以你可以使用
static getDerivedStateFromError(error: Error) {
// ...
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
// ...
}
GetDerivedStateFromError
类型如下所示,我认为它的错误类型不应该是 type ,any
而且应该是 typeError
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;
推荐阅读
- ios - 具有白色背景的材料设计大纲文本字段
- python - 使用 REST API 问题将文件上传到 imgur.com
- javascript - 将 TypeScript 与 Jest 一起使用不会捕获语法错误
- r - networkD3 和 Shiny - 按节点数过滤
- mysql - 如何使用 MySQL 和 T-SQL 获得一对多的关系类型
- python - 在 Heroku 上使用 python discord bot 调用 C 二进制文件
- amazon-web-services - cloudformation中ecs服务的问题:提供的target group有target type instance,与awsvpc网络不兼容
- javascript - 通过 addEventListener 传递它
- docker - 在 CI 中运行时的 docker-compose 竞争条件
- django - 如何表达日期时间高于或低于 30 天 django