设置倒数计时器React JS 基于类的实现功能组件的实现

问题描述

我想将倒数计时器设置为从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分钟重复一次。有人可以帮助我吗?

解决方法

使用setInterval会让我很头疼,想一想每次在响应重绘过程之后每次都发生了什么,并将越来越多的间隔添加到事件循环中,我建议将setTimeout与componentDidUpdate方法一起使用状态,最后清理或使用挂钩使生活更轻松

这是带有钩子的解决方案


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,...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} />;
};

Edit 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>
    )
}