【问题标题】:Using setInterval in React isn't working as expected在 React 中使用 setInterval 没有按预期工作
【发布时间】:2020-07-03 04:57:10
【问题描述】:

我正在尝试使用 React 钩子制作一个倒数计时器。计时器的秒部分按预期工作,但在更新分钟部分时遇到问题。在下面的示例中,我希望计时器从 05:00 开始,然后单击按钮更新到 04:59、04:58 等。但是当我单击按钮时,它没有给出 04:59,而是给出了 03:59。下面附上相同的代码。请让我知道我哪里弄错了。

import React, { useState } from "react";

const padWithZero = num => {
  const numStr = num.toString();
  return numStr.length === 1 ? "0" + numStr : numStr;
};

const Clock = () => {
  let timer;
  const [mins, setMins] = useState(5);
  const [secs, setSecs] = useState(0);
  const startHandler = () => {
    timer = setInterval(() => {
      setSecs(prevSecs => {
        if (prevSecs === 0) {
          setMins(prevMins => prevMins - 1);
          return 59;
        } else return prevSecs - 1;
      });
    }, 1000);
  };
  return (
    <div>
      <h1>{`${padWithZero(mins)}:${padWithZero(secs)}`}</h1>
      <button onClick={startHandler}>Start</button>
    </div>
  );
};

export default Clock;

【问题讨论】:

  • 我真的不知道它应该如何工作。在点击动作之后,它应该从5:00 开始计时并下降到零?然后当再次单击按钮时,它应该将计时器重置为5:00 并再次归零?
  • @SMAKSS,是的,如果我点击开始,它应该从 05:00 开始,并且应该继续递减,没有添加在 00:00 停止的逻辑

标签: reactjs react-hooks setinterval clearinterval


【解决方案1】:

我不知道为什么它将您的分钟数从 5 分钟减少到 4 分钟,从 4 分钟减少到 3 分钟。

但我修改了您的代码并添加了重置功能 - 每次点击按钮都会将计时器重置为初始 5:00。现在它可以正常工作了:

import React, { useState } from "react";

const padWithZero = num => {
  const numStr = num.toString();
  return numStr.length === 1 ? "0" + numStr : numStr;
};

const INIT_SECS = 0;
const INIT_MINS = 5;

const Clock = () => {
    let timer;
    const [mins, setMins] = useState(INIT_MINS);
    const [secs, setSecs] = useState(INIT_SECS);
    const [storedTimer, setStoredTimer] = useState(null);

    const startHandler = () => {
        if (storedTimer) {
            clearInterval(storedTimer);
            setMins(INIT_MINS);
            setSecs(INIT_SECS);
        }
        const newTimer = setInterval(() => {
            setSecs(prevSecs => {
                if (prevSecs === 0) {
                    setMins(prevMins => prevMins - 1);
                    return 59;
                } else return prevSecs - 1;
            });
        }, 1000);

        setStoredTimer(newTimer);
    };

    return (
        <div>
            <h1>{`${padWithZero(mins)}:${padWithZero(secs)}`}</h1>
            <button onClick={startHandler}>Start</button>
        </div>
    );
};
export default Clock;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2021-09-03
    • 1970-01-01
    • 2022-08-16
    • 2023-03-16
    相关资源
    最近更新 更多