Javascript 如何在我的ReactJS应用程序中添加倒计时

Javascript 如何在我的ReactJS应用程序中添加倒计时,javascript,node.js,reactjs,react-native,Javascript,Node.js,Reactjs,React Native,我是ReactJS新手,尝试实现倒计时,但在我的中,我需要刷新页面以显示实际的倒计时。 这里我有两个约会时间(1)未来日期时间和(2)当前日期时间,我需要根据这些日期时间的不同显示不同的状态。 (a) 。如果未来日期和今天日期相同,我的状态将是今天 (b) 。如果距离到达未来日期还有1小时,那么我需要显示59:59的倒计时计时器 (c) 。一旦倒计时结束,我的状态将为“现场” 任何帮助都将不胜感激。提前谢谢 import React, { useEffect, useRef, useState

我是ReactJS新手,尝试实现倒计时,但在我的中,我需要刷新页面以显示实际的倒计时。 这里我有两个约会时间(1)未来日期时间和(2)当前日期时间,我需要根据这些日期时间的不同显示不同的状态。 (a) 。如果未来日期和今天日期相同,我的状态将是今天 (b) 。如果距离到达未来日期还有1小时,那么我需要显示59:59的倒计时计时器 (c) 。一旦倒计时结束,我的状态将为“现场”

任何帮助都将不胜感激。提前谢谢

import React, { useEffect, useRef, useState } from "react";
import moment from "moment";

let sDate = "2021-04-26T18:46:00.000Z";
let formatted_sDate = moment(sDate).utc().format("MM/DD/YYYY HH:mm:ss");
let eDate = moment(new Date()).format("MM/DD/YYYY HH:mm:ss");
const ONE_HOUR = 3600;

// compare two dates & get diff in days
function getDateDifferenceInDays(s, e) {
  const sDate = moment(s);
  const eDate = moment(e);
  const days = sDate.diff(eDate, "days");
  return days;
}

// compare two dates & get diff in seconds
function getTimeDifferenceInSeconds(s, e) {
  const sDate = moment(s);
  const eDate = moment(e);
  const seconds = sDate.diff(eDate, "seconds");
  return seconds;
}

function format(time) {
  // Hours, minutes and seconds
  var hrs = ~~(time / 3600);
  var mins = ~~((time % 3600) / 60);
  var secs = ~~time % 60;

  // Output like "1:01" or "4:03:59" or "123:03:59"
  var ret = "";
  if (hrs > 0) {
    ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
  }
  ret += "" + mins + ":" + (secs < 10 ? "0" : "");
  ret += "" + secs;
  return ret;
}

export default function App() {
  const timerBeforeCountDown = useRef();
  const currentTimer = useRef();
  const [time, setTime] = useState(null);
  const [startCurrentTimer, setStartCurrentTimer] = useState(false);

  useEffect(() => {
    const diffInDays = getDateDifferenceInDays(formatted_sDate, eDate);
    const diffInSeconds = getTimeDifferenceInSeconds(formatted_sDate, eDate);

    if (diffInDays === 0) {
      if (diffInSeconds > ONE_HOUR) {
        setTime(diffInSeconds);
        setStartCurrentTimer(false);
        timerBeforeCountDown.current = setInterval(() => {
          setTime((prev) => {
            if (prev > ONE_HOUR) {
              return prev - 1;
            } else {
              setStartCurrentTimer(true);
              clearInterval(timerBeforeCountDown.current);
            }
          });
        }, 1000);
      } else if (diffInSeconds <= ONE_HOUR && diffInSeconds > 0) {
        setTime(diffInSeconds);
        setStartCurrentTimer(true);

        currentTimer.current = setInterval(() => {
          if (time > 0) {
            setTime((prev) => {
              if (prev > 0) {
                return prev - 1;
              } else {
                return prev;
              }
            });
          } else {
            clearInterval(currentTimer.current);
          }
        }, 1000);
      } else {
        return null;
      }
    } else {
      return null;
    }

    // clear intervel
    return () => {
      clearInterval(timerBeforeCountDown.current);
      clearInterval(currentTimer.current);
    };
  }, [startCurrentTimer]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{time !== null && time > ONE_HOUR && "TODAY"}</h2>
      <h2>{time !== null && time <= ONE_HOUR && time > 0 && format(time)}</h2>
      <h2>{time === 0 && "LIVE"}</h2>
    </div>
  );
}
import React,{useffect,useRef,useState}来自“React”;
从“时刻”中导入时刻;
让sDate=“2021-04-26T18:46:00.000Z”;
设格式化的_sDate=时刻(sDate).utc().format(“MM/DD/YYYY HH:MM:ss”);
设eDate=moment(new Date()).format(“MM/DD/YYYY HH:MM:ss”);
常数一小时=3600;
//比较两个日期并以天为单位获得差异
函数getDateDifferenceDays(s,e){
常数=力矩;
常数=力矩(e);
施工天数=日期差异(日期,“天”);
返程天数;
}
//比较两个日期并以秒为单位获得差异
函数getTimeDifferenceSeconds(s,e){
常数=力矩;
常数=力矩(e);
常数秒=数据差异(数据,秒);
返回秒数;
}
函数格式(时间){
//小时、分钟和秒
var hrs=~(时间/3600);
var分钟=~(时间%3600)/60);
var secs=~~时间%60;
//输出如“1:01”或“4:03:59”或“123:03:59”
var ret=“”;
如果(小时数>0){
ret+=“+hrs+”:“+(分钟<10?:”);
}
ret+=“+mins+”:“+(秒<10?:”);
ret+=“”+秒;
返回ret;
}
导出默认函数App(){
const timerBeforeCountDown=useRef();
const currentTimer=useRef();
const[time,setTime]=useState(null);
常量[startCurrentTimer,setStartCurrentTimer]=useState(false);
useffect(()=>{
const diffInDays=getDateDifferenceInDays(格式化的数据,eDate);
const diffinsionds=getTimeDifferenceSeconds(格式化的数据,eDate);
如果(diffInDays==0){
如果(不同强度>一小时){
设定时间(不确定度);
setStartCurrentTimer(错误);
TimerBeforReconntDown.current=setInterval(()=>{
设置时间((上一个)=>{
如果(上一次>一小时){
返回prev-1;
}否则{
setStartCurrentTimer(真);
clearInterval(TimerBeforRecountDown.current);
}
});
}, 1000);
}else if(diffinsonds 0){
设定时间(不确定度);
setStartCurrentTimer(真);
currentTimer.current=setInterval(()=>{
如果(时间>0){
设置时间((上一个)=>{
如果(上一个>0){
返回prev-1;
}否则{
返回上一个;
}
});
}否则{
clearInterval(currentTimer.current);
}
}, 1000);
}否则{
返回null;
}
}否则{
返回null;
}
//清晰的中间层
return()=>{
clearInterval(TimerBeforRecountDown.current);
clearInterval(currentTimer.current);
};
},[startCurrentTimer]);
返回(
你好,代码沙盒
{time!==null&&time>1小时&&day}
{time!==null&&time 0&&format(time)}
{time==0&&“LIVE”}
);
}

这里有很多事情要做,你不需要时间。因为你是新来的,我把你的回购协议分成了两半,这样你就可以看到一个更简单的方法来实现同样的目标。您在返回中的支票也将始终返回内容

import { useEffect, useState } from "react";

export const useCountdownTimer = (date) => {
  const [seconds, setTimer] = useState(date - Date.now());
  useEffect(() => {
    const timeout = setTimeout(() => setTimer(seconds - 1), 1000);
    if (seconds <= 0) clearTimeout(timeout);
    return () => {
      clearTimeout(timeout);
    };
  }, [seconds]);

  const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, "0");
  const s = Math.floor(seconds % 60).toString().padStart(2, "0");

  return {
    seconds,
    time: `${m}:${s}`
  };
};

export default function App() {
  // const date = new Date("2021-04-26T18:46:00.000Z").getTime();
  const date = Date.now() + 3603; // 1 hour & 3 seconds from now for demo
  const { seconds, time } = useCountdownTimer(date); // date must be in seconds
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {!!seconds && seconds >= 3600 && <h2>TODAY</h2>}
      {!!seconds && seconds < 3600 && <h2>{time}</h2>}
      {seconds <= 0 && <h2>LIVE</h2>}
    </div>
  );
}
从“react”导入{useffect,useState};
导出常量useCountdownTimer=(日期)=>{
const[seconds,setTimer]=useState(date-date.now());
useffect(()=>{
const timeout=setTimeout(()=>setTimer(秒-1),1000);
如果(秒){
clearTimeout(超时);
};
},[秒];
常数m=数学地板((秒%3600)/60).toString().padStart(2,“0”);
const s=Math.floor(秒数%60).toString().padStart(2,“0”);
返回{
秒,
时间:`${m}:${s}`
};
};
导出默认函数App(){
//const date=新日期(“2021-04-26T18:46:00.000Z”).getTime();
const date=date.now()+3603;//从现在开始演示1小时3秒
const{seconds,time}=useCountdownTimer(日期);//日期必须以秒为单位
返回(
你好,代码沙盒
{!!秒和秒>=3600秒和今天}
{!!秒&&seconds<3600&&{time}

{秒您需要将
time
添加到useEffect挂钩依赖项数组,而不是startCurrentTimer。每次更新
time
时,状态都需要更新。