设置倒数计时器 React JS

IT技术 javascript reactjs timer
2021-05-22 02:35:10

我想设置倒数计时器在 00:00 开始并每 5 分钟重复一次。(例如:当时间是 00:05 时,计时器倒计时 5 分钟,直到 00:10,在 00:10 再次倒计时 5 分钟,依此类推)

这是我现在的代码:

  class App extends React.Component {
   constructor(props) {
   super(props);
    this.state = {
    minutes: 5,
    seconds: 0
  };
 }

 ...............

    componentDidMount() {
      this.getData();

      this.myInterval = setInterval(() => {
        const { seconds, minutes } = this.state
        if (seconds > 0) {
          this.setState(({ seconds }) => ({
            seconds: seconds - 1
          }))
        }
        if (seconds === 0) {
          if (minutes === 0) {
            clearInterval(this.myInterval)
          } else {
            this.setState(({ minutes }) => ({
              minutes: minutes - 1,
              seconds: 59
            }))
          }
        }
      }, 1000)

    }

 ...........

 return (
   <p>Countdown : {this.state.minutes}:{this.state.seconds < 10 ? `0${this.state.seconds}` : this.state.seconds} </p>

    );
  }
}

我应该在哪里更改或添加以使倒计时从 00:00 开始并每 5 分钟重复一次。任何人都可以帮助我吗?

3个回答

使用setInterval会让我很头疼地弄清楚每次在react重新渲染过程之后发生了什么,并且越来越多的间隔被添加到事件循环中,我建议使用setTimeoutcomponentDidUpdate 方法来更新状态并在最后清理或使用钩子生活更轻松

这是一个带钩子的解决方案


function App() {

  const [seconds, setSeconds] = useState(0)
  const [minutes, setMinutes] = useState(5)



  function updateTime() {
    if (minutes == 0 && seconds == 0) {
      //reset
      setSeconds(0);
      setMinutes(5);
    }
    else {
      if (seconds == 0) {
        setMinutes(minutes => minutes - 1);
        setSeconds(59);
      } else {
        setSeconds(seconds => seconds - 1);
      }
    }
  }



  useEffect(() => {
    // use set timeout and be confident because updateTime will cause rerender
    // rerender mean re call this effect => then it will be similar to how setinterval works
    // but with easy to understand logic
    const token = setTimeout(updateTime, 1000)

    return function cleanUp() {
      clearTimeout(token);
    }
  })




  return (<p>
    time: {minutes}:{seconds}
  </p>);
}

我建议创建和跟踪单个时间状态,即秒,每秒递增,并简单地计算要显示的分钟和秒。

分钟

String(Math.floor(time / 60)).padStart(2, '0'); // 00, 01, 02, ...59

String(time % 60).padStart(2, '0'); // 00, 01, 02, ...59

倒计时时间可以通过从每个间隔减去每个间隔的秒余数来计算,即 300 - time % 300

RESET_INTERVAL_S - time % RESET_INTERVAL_S

给定一个显示整体计时器和倒数计时器的组件,以及一个呈现格式化时间的实用函数

const formatTime = (time) =>
  `${String(Math.floor(time / 60)).padStart(2, "0")}:${String(
    time % 60
  ).padStart(2, "0")}`;

const Timer = ({ time }) => {
  const timeRemain = RESET_INTERVAL_S - (time % RESET_INTERVAL_S);

  return (
    <>
      <div>Time: {formatTime(time)}</div>
      <div>Countdown Timer: {formatTime(timeRemain)}</div>
    </>
  );
};

基于类的实现

class IntervalTimerClass extends Component {
  state = {
    time: 0
  };

  timerId = null;

  componentDidMount() {
    this.timerId = setInterval(() => {
      this.setState((prevState) => ({ time: prevState.time + 1 }));
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerId);
  }

  render() {
    return <Timer time={this.state.time} />;
  }
}

功能组件实现

const IntervalTimerFunctional = () => {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const timerId = setInterval(() => {
      setTime((t) => t + 1);
    }, 1000);
    return () => clearInterval(timerId);
  }, []);

  return <Timer time={time} />;
};

编辑 set-countdown-timer-react-js

import {useState} from 'react'

设置常量

function Timer(){
const[timer, setTimer] = useState(121)

const sec = timer%60 //set seconds
const min = timer/60 //set minutes
const clock = `${min}:${sec > 9: sec: '0'+sec}` //create 'clock'

const startTimer =  //now start the 'timer'
timer > -1?

setTimeout(()=>{
  setTimer(timer-1), setTimer(clock)
},1000):'done'

 if(timer === 0 && min === 0 && sec === 0){
     console.log('you done')
    }

if(timer && min === 0 && sec === 0 ){
  min -=1
  sec += 59
}



    return(
    <div>{timer}</div>
    )
}