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
不要依赖于设置延迟为5000ms的setTimeOut函数,考虑使用时间戳。您可以将时间戳保存在localStorage中,然后与当前时间戳进行比较。如果差值等于或大于5000ms,则重新启用按钮。以下是完整的代码和我的实现:
您只需要为'0'设置一个额外的if语句检查来禁用。您已经正确地存储了该值。