避免在Reactjs中刷新時重置超時時間
P粉285587590
P粉285587590 2023-09-07 20:50:48
0
2
568

有一個按鈕,點擊3次後會被停用。當我刷新頁面時,計數器保持不變(1/3、2/3或0/3)。但是我無法對禁用的按鈕做同樣的操作。我不想重設setTimeout。我希望它能從離開時的時間繼續。

import React, { useEffect, useState } from 'react'

function Without() {

//const [count, setCount] = useState(3);
const [count, _setCountValue] = useState(3);

const [disable, setDisable] = useState(false);

function setCount(value) {
  localStorage.setItem('count', JSON.stringify(value))
  return _setCountValue(value)
}


const handleDec = () => {
    if (count > 1) {
      setCount(count - 1);
    } else {
      setCount(0);
      setDisable(true);
      const timeout = setTimeout(() => {
        setDisable(false);
        setCount(3);
      }, 5000);
      return () => clearTimeout(timeout); 
    }
  };


  //LOCALSTORAGE
  useEffect(() => {
    const storedCount = localStorage.getItem('count');
    if (storedCount) {
      setCount(parseInt(storedCount));
    }
  }, []);


  return (
    <div>

      <h3>{count} / 3</h3>
      <button disabled={disable} onClick={handleDec}>
        Remaining Use
      </button>

    </div>
  )
}

export default Without
P粉285587590
P粉285587590

全部回覆(2)
P粉463811100

不要依賴設定延遲為5000ms的setTimeOut函數,考慮使用時間戳記。您可以將時間戳記儲存在localStorage中,然後與目前時間戳記進行比較。如果差值等於或大於5000ms,則重新啟用按鈕。以下是完整的程式碼和我的實作:

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

function Without() {
  const [count, setCount] = useState(3);
  const [disable, setDisable] = useState(false);

  const handleDec = () => {
    if (count > 1) {
      setCount(count - 1);
    } else {
      setCount(0);
      setDisable(true);
      const timestamp = new Date().getTime(); // 获取当前时间戳
      localStorage.setItem("disabledTimestamp", timestamp);
    }
  };

  // 检查按钮被禁用后是否已经过了5秒
  useEffect(() => {
    const disabledTimestamp = localStorage.getItem("disabledTimestamp");
    if (disabledTimestamp) {
      const currentTime = new Date().getTime();
      const fiveSecondsInMillis = 5000;
      const difference = currentTime - parseInt(disabledTimestamp, 10);

      if (difference < fiveSecondsInMillis) {
        setDisable(true);
        const timeout = setTimeout(() => {
          setDisable(false);
          setCount(3);
          localStorage.removeItem("disabledTimestamp"); // 重新启用按钮后重置时间戳
        }, fiveSecondsInMillis - difference);

        return () => clearTimeout(timeout);
      } else {
        setDisable(false);
        localStorage.removeItem("disabledTimestamp"); // 如果超过5秒则重置时间戳
      }
    }
  }, [disable]);

  // LOCALSTORAGE
  useEffect(() => {
    const storedCount = localStorage.getItem("count");
    if (storedCount) {
      setCount(parseInt(storedCount));
    }
  }, []);

  return (
    <div>
      <h3>{count} / 3</h3>
      <button disabled={disable} onClick={handleDec}>
        剩余使用次数
      </button>
    </div>
  );
}

export default Without;
P粉184747536

您只需要為'0'設定一個額外的if語句檢查來停用。您已經正確地儲存了該值。

//LOCALSTORAGE
  useEffect(() => {
    const storedCount = localStorage.getItem('count');
    console.log("storedcount: ", storedCount);
    if (storedCount) {
      setCount(parseInt(storedCount));
      if (storedCount === '0') {
        setDisable(true);
      }
    }
  }, []);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板