有一个按钮,在点击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 Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
不要依赖于设置延迟为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;您只需要为'0'设置一个额外的if语句检查来禁用。您已经正确地存储了该值。
//LOCALSTORAGE useEffect(() => { const storedCount = localStorage.getItem('count'); console.log("storedcount: ", storedCount); if (storedCount) { setCount(parseInt(storedCount)); if (storedCount === '0') { setDisable(true); } } }, []);