Heim  >  Fragen und Antworten  >  Hauptteil

Vermeiden Sie das Zurücksetzen des Timeouts bei der Aktualisierung in Reactjs

Es gibt eine Schaltfläche, die nach 3 Klicks deaktiviert wird. Wenn ich die Seite aktualisiere, bleibt der Zähler gleich (1/3, 2/3 oder 0/3). Aber mit deaktivierten Tasten ist das nicht möglich. Ich möchte setTimeout nicht zurücksetzen. Ich hoffe, es macht dort weiter, wo ich aufgehört habe.

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粉285587590P粉285587590384 Tage vor502

Antworte allen(2)Ich werde antworten

  • P粉463811100

    P粉4638111002023-09-08 00:28:18

    不要依赖于设置延迟为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;

    Antwort
    0
  • P粉184747536

    P粉1847475362023-09-08 00:18:30

    您只需要为'0'设置一个额外的if语句检查来禁用。您已经正确地存储了该值。

    //LOCALSTORAGE
      useEffect(() => {
        const storedCount = localStorage.getItem('count');
        console.log("storedcount: ", storedCount);
        if (storedCount) {
          setCount(parseInt(storedCount));
          if (storedCount === '0') {
            setDisable(true);
          }
        }
      }, []);

    Antwort
    0
  • StornierenAntwort