React useEffect 钩子不清除间隔

xua*_*yue 2 reactjs

我正在尝试使用反应钩子来构建一个简单的倒数计时器来倒计时 3 秒。但是在 3 秒后 UI 停止渲染但在 console.log 中我仍然可以每秒打印一次。为什么 useEffect 中的第二个数组参数不能阻止这种情况发生?

代码沙箱

function CounterGame() {
  const [timeout, setTimeout] = React.useState(3);

  React.useEffect(() => {
    let id = window.setInterval(() => {
      if (timeout > 0) {
        setTimeout(x => x - 1 );
      }
      // this line keep executing even it timeout reach 0
      console.log("in setInterval", timeout);
    }, 1000)

    return () => {
      window.clearInterval(id);
    }
  }, [timeout])
  return (
    <div className="App">
      See instructions.
      <h1>{timeout} seconds</h1>
      {!timeout && <button>Click</button>}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<CounterGame />, rootElement);
Run Code Online (Sandbox Code Playgroud)

小智 5

这可能对您有用:

通过在 useEffect 中添加条件,当超时为零时 clearIntervel

React.useEffect(() => {
      let id = window.setInterval(() => {
        if (timeout > 0) {
          setTimeout(x => x - 1 );
        }

    //clearIntervel here
        if(timeout == 0){
            window.clearInterval(id);
        }

        // this line keep executing even it timeout reach 0
        console.log("in setInterval", timeout);
      }, 1000)
  
      return () => {
        window.clearInterval(id);
      }
    }, [timeout])
Run Code Online (Sandbox Code Playgroud)