setInterval 在 React 中更新状态但无法识别时间何时为 0 [英] setInterval updating state in React but not recognizing when time is 0

查看:87
本文介绍了setInterval 在 React 中更新状态但无法识别时间何时为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

import React, {useState } from 'react';功能应用(){const [seconds, setSeconds] = useState(10);const startTimer = () =>{const 间隔 = setInterval(() => {setSeconds(seconds => seconds - 1);//每次记录 10控制台日志(秒)//永远不满足这个条件如果(秒 === 0){清除间隔(间隔)}}, 1000);}返回 (<div><button onClick={() =>startTimer()}></button>//更新当前秒数<p>{秒}</p>

)}导出默认应用程序;

解决方案

那是因为 setSeconds 在每个刻度上用一个新变量更新状态,但初始引用(秒 === 10)仍然指向初始设置变量.这就是为什么它保持在 10 =>初步参考.要获取当前值,您必须在 setSeconds 变量(以秒形式传递)中检查它,如下所示:

const startTimer = () =>{const 间隔 = setInterval(() => {设置秒(秒 => {如果(秒<1){清除间隔(间隔);返回 10;}返回秒数 - 1;});}, 1000);}

这是一个有效的沙盒

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

I am practicing React useState hooks to make a quiz timer that resets every ten seconds. What I have now is updating the state each second, and the p tag renders accordingly. But when I console.log(seconds) it shows 10 every time, and so the condition (seconds === 0) is never met . In Chrome's React DevTools, the state is updating accordingly as well. What am I doing wrong here?

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;

解决方案

That is because the setSeconds updates the state with a new variable on every tick but the initial reference (seconds === 10) still points to the initial set variable. That is why it stays at 10 => The initial reference. To get the current value, you have to check it in the setSeconds variable (passed as seconds) like this:

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

Here is a working sandbox

You should also rename the variable to not have the same name (seconds) twice in a single funtion.

这篇关于setInterval 在 React 中更新状态但无法识别时间何时为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆