如何在React中显示倒数计时器

时间:2020-05-14 07:04:29

标签: reactjs react-hooks

如何以分钟和秒为单位显示倒数计时器。现在,我只能以秒为单位显示计时器,但是我想同时显示分钟和秒。

当前我的倒数计时器以这种方式显示Countdown: 112,但我希望它像Countdown: 1: 52

import React from "react";

export default function App() {
  const [counter, setCounter] = React.useState(120);
  React.useEffect(() => {
    counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
  }, [counter]);

  return (
    <div className="App">
      <div>Countdown: {counter === 0 ? "Time over" : counter}</div>
    </div>
  );
}

4 个答案:

答案 0 :(得分:1)

这是格式化时间的完整解决方案:

// Prepend `0` for one digit numbers. For that the number has to be
// converted to string, as numbers don't have length method
const padTime = time => {
  return String(time).length === 1 ? `0${time}` : `${time}`;
};

const format = time => {
  // Convert seconds into minutes and take the whole part
  const minutes = Math.floor(time / 60);

  // Get the seconds left after converting minutes
  const seconds = time % 60;

  //Return combined values as string in format mm:ss
  return `${minutes}:${padTime(seconds)}`;
};

export default function App() {
  const [counter, setCounter] = React.useState(120);
  React.useEffect(() => {
    let timer;
    if (counter > 0) {
      timer = setTimeout(() => setCounter(c => c - 1), 1000);
    }

    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [counter]);

  return (
    <div className="App">
      {counter === 0 ? "Time over" : <div>Countdown: {format(counter)}</div>}
    </div>
  );
}

关于原始代码的一些注意事项:

  1. 由于counter的下一个值取决于前一个值,因此最好使用setState的功能形式。
  2. 在卸载组件时清除超时是一个好习惯。

答案 1 :(得分:0)

将您的setCounter方法更改为关注方法即可。

React.useEffect(() => {
    counter !== 'Time Over' && setTimeout(() => setCounter(counter > 1 ? counter - 1 : 'Time Over'), 1000);
}, [counter]);

答案 2 :(得分:0)

可以这样做:

import React from "react";

export default function App() {
  const [counter, setCounter] = React.useState(120);
  React.useEffect(() => {
    counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
  }, [counter]);

  return (
    <div className="App">
      <div>Countdown: {counter === 0 ? "Time over" : counter}</div>
    </div>
  );
}

答案 3 :(得分:0)

从导入阶段导入钩子:

Hooks react

import React, 

{useState,useEffect}

来自“反应”;

export default function App() {
  const [counter, setCounter] = useState(120);
  useEffect(() => {
    counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
  }, [counter]);

  return (
    <div className="App">
      <div>Countdown: {counter === 0 ? "Time over" : counter}</div>
    </div>
  );
}