javascript - useEffect - 在 setInterval 中调用函数
问题描述
如何在 useEffect 的 setInterval 中调用函数
useEffect(() => {
const timeoutId = setInterval(() => {getTime}, 1000); // this is Line 8
return function cleanup() {
clearTimeout(timeoutId);
}
}, [getTime]);
const getTime=() =>{
console.log("Inside getTime");}
我希望每 1 秒调用一次我的 getTime 函数。我得到以下错误
Line 8:46: Expected an assignment or function call and instead saw an expression no-unused-expressions.
另一个问题,我想每 1 秒更新一次状态,我可以在 setInterval 中更新状态吗
解决方案
如果getTime()
是 setInterval 的唯一功能,您可以这样做
const timeoutId = setInterval(getTime, 1000);
或者如果您在 setInterval 函数中还有其他命令getTime()
要做,则如下所示。
const timeoutId = setInterval(() => {getTime()}, 1000);
推荐阅读
- php - Outlook 电子邮件正在自动执行激活链接
- android - Android Studio 在 XML 中将 Switch 添加到 textview 的左侧
- amazon-web-services - 使用客户端身份验证将经典 ELB 连接到 EC2 Tomcat
- python - 可以使用 pylint 标记未使用的全局变量吗?
- python - 以 csv 格式下载 google bigquery 数据
- javascript - 如何通过使用 setInterval 方法调用函数来打印时钟的指针
- python - 如何从 CLI 安装和运行 Pyright 而不是使用 VS Code?
- ruby-on-rails - 重命名涉及属于关联 id 的强参数
- sql - 从 Oracle 中的日期获取季度的问题
- google-cloud-platform - GKE 堆栈驱动程序跟踪报告按集群按环境按服务按服务版本