在使用钩子进行反应的coundown计时器上格式化时间时出现问题

问题描述 投票:1回答:1

尝试使用简单的倒计时计时器,使分钟和秒数过期,并在需要时重新加载按钮以将其重置,但是我一直坚持以正确的格式解析时间。这是我所做的实时预览:https://codesandbox.io/s/bold-poitras-t85mt?file=/src/App.js:0-654

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [countdown, setCountdown] = useState({
    expirityTime: 10,
    expired: false
  });

  useEffect(() => {
    let time = countdown.expirityTime;
    if (time > 0) {
      const timerId = setTimeout(() => {
        setCountdown({ expirityTime: time - 1 });
      }, 1000);
      return () => clearTimeout(timerId);
    }
  });

  return (
    <div className="App">
      <div className="timer">Time Remaining: {countdown.expirityTime}</div>
      <button onClick={e => setCountdown({ expirityTime: 10 })}>Reset</button>
    </div>
  );
}

将很高兴获得任何帮助。尝试let time = countdown.expirityTime * 60;首先将时间设置为秒到分钟,但是每次下一次setCountdown调用的结果都会相乘。我真的被卡住了。

javascript reactjs react-hooks
1个回答
0
投票

如果您以秒为单位存储所有状态,即120s == 2分钟,那么您只需要做一些简单的数学运算就可以计算分钟和秒。

minutes = Math.floor(time / 60)
seconds = time % 60

所以您的渲染可能是

<div className="timer">
  Time Remaining: {Math.floor(countdown.expirityTime / 60)}:
  {countdown.expirityTime % 60}
</div>
<button onClick={e => setCountdown({ expirityTime: 120 })}>Reset</button>

Edit countdown time minutes:seconds

© www.soinside.com 2019 - 2024. All rights reserved.