首页 > 解决方案 > 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 中更新状态吗

标签: javascriptreactjssetintervaluse-effect

解决方案


如果getTime()是 setInterval 的唯一功能,您可以这样做

        const timeoutId = setInterval(getTime, 1000);

或者如果您在 setInterval 函数中还有其他命令getTime()要做,则如下所示。

        const timeoutId = setInterval(() => {getTime()}, 1000);

推荐阅读