簡體   English   中英

如何在我的 ReactJS 應用程序中添加倒數計時器

[英]How can I add Countdown Timer in my ReactJS app

我是 ReactJS 的新手並嘗試實現倒數計時器,但在我當前的代碼中,我需要刷新頁面以顯示實際的倒計時。 這里我有兩個日期時間(1)。 未來的日期時間和 (2)。 當前日期時間,我需要根據這些日期時間的差異顯示不同的狀態 (一個)。 如果未來日期和今天日期相同,我的狀態將是今天(b)。 如果距離未來日期還有1 小時,那么我需要從 59:59 (c) 開始顯示倒數計時器。 一旦倒計時結束,我的狀態將是LIVE

任何幫助將不勝感激。 提前致謝..

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 { 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>
  );
}

https://codesandbox.io/s/reactcounterv2-forked-fsnwr?file=/src/App.js

如果您需要源代碼,請嘗試此https://www.npmjs.com/package/@nilevia/count-down-timer-react,go到 ZBF215181B51405221437B3D4F6B73 頁

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM