setInterval 在 React 中更新状态但无法识别时间何时为 0

setInterval updating state in React but not recognizing when time is 0

我正在练习 React useState 挂钩来制作一个每十秒重置一次的测验计时器。我现在拥有的是每秒更新状态,并且 p 标签相应地呈现。但是当我 console.log(seconds) 它每次都显示 10,所以永远不会满足条件 (seconds === 0) 。在 Chrome 的 React DevTools 中,状态也在相应地更新。我在这里做错了什么?

import React, {useState } from 'react';

function App() {

  const [seconds, setSeconds] = useState(10);

  const startTimer = () => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds - 1);

      // Logs 10 every time
      console.log(seconds)

      // Never meets this condition
      if (seconds === 0) {
            clearInterval(interval)
      }
    }, 1000);
  }

  return (
    <div>
      <button onClick={() => startTimer()}></button>
      // updates with current seconds
      <p>{seconds}</p>
    </div>
  )
}

export default App;

这是因为 setSeconds 在每次更新时都会用一个新变量更新状态,但初始引用(秒 === 10)仍然指向初始设置变量。这就是为什么它停留在 10 => 初始引用。 要获取当前值,您必须像这样在 setSeconds 变量(以秒为单位传递)中检查它:

const startTimer = () => {
    const interval = setInterval(() => {
      setSeconds(seconds => {
        if(seconds < 1) {
          clearInterval(interval);
          return 10;
        }
        return seconds - 1;
      });
    }, 1000);
  }

这是一个有效的sandbox

您还应该将变量重命名为在单个函数中不具有相同的名称(秒)两次。