reactjs - '() => Timeout' 类型的参数不能分配给 'number' 类型的参数
问题描述
我正在尝试使用 React 和 TypeScript 清除超时,componentWillUnmount
但出现以下错误:
Argument of type '() => Timeout' is not assignable to parameter of type 'number'.ts(2345)
这是我的代码:
startPolling = (): ReturnType<typeof setTimeout> => setTimeout(() => this.loadData(), this.getTimeout());
componentWillUnmount = (): void => {
clearTimeout(this.startPolling); // error is thrown here
}
我很困惑如何摆脱这个错误。我的代码有什么问题?TIA。
解决方案
错误是说clearTimeout()
需要一个数字,但您正在传递一个函数。MDN 文档说该参数是“您要取消的超时的标识符”。setTimeout()
返回可在此处使用的 id。您需要保存返回值以供以后调用时使用clearTimeout()
。
推荐阅读
- excel - 将分组数据(实体)从源工作表(受保护)复制到另一个
- android - 如何解决 FragmentNavigator 忽略功能的问题?
- excel - VBA用户表单从选定的文件夹位置复制pdf
- python-3.x - 为什么当我使用“ from module import *”并且我想通过帮助(模块)查看模块的功能时它不起作用?
- django - 运行 runserver 时出现“LookupError: No installed app with label 'admin'”。发生
- r - R中的时间序列标签
- google-app-engine - Google Cloud Endpoints 和 App Engine 的延迟在 1 到 2 秒之间是否正常?
- python - Google Cloud ML-Engine 在线预测错误:为已包含的占位符张量提供值
- java - FileOutputStream try-with-resources 不关闭文件描述符
- django - 使用 UniqueConstraint 解决 Django admin 中的“get() 返回多个”错误