[英]Show countdown when holding button then show alert
我正在嘗試創建一個按鈕,當按住時顯示 3 秒的倒計時,如果保持 3 秒它會顯示警報,但由於某種原因倒計時沒有正確重置並且警報無論如何都會觸發,在每次點擊(超時后)
我的代碼是:
const [showCountdown, setShowCountdown] = useState(false)
const [holdTimer, setHoldTimer] = useState(3)
var timer = 0, interval;
const refreshDown = () => {
setShowCountdown(true)
interval = setInterval(function(){
setHoldTimer((t) => t - 1)
},1000);
timer = setTimeout(function(){
if (confirm('Refresh page?')){
window.location.reload()
}
},3000)
}
const refreshUp = () => {
clearTimeout(timer)
clearInterval(interval)
setShowCountdown(false)
setHoldTimer(3)
}
我的 html 按鈕有這兩個:
<svg onMouseDown={() => refreshDown()} onMouseUp={() => refreshUp()}>
...
</svg>
您是否嘗試過useRef
?
const timer = useRef();
const interval = useRef();
const refreshDown = () => {
setShowCountdown(true);
interval.current = setInterval(function () {
setHoldTimer((t) => t - 1);
}, 1000);
timer.current = setTimeout(function () {
if (confirm("Refresh page?")) {
window.location.reload();
}
}, 3000);
};
const refreshUp = () => {
clearTimeout(timer.current);
clearInterval(interval.current);
setShowCountdown(false);
setHoldTimer(3);
};
每次 state 或更改道具時,都會重新渲染 React 組件。 當 setHoldTimer 被執行時,它改變了 state。它導致組件代碼的重新執行,所以局部變量“timer”和“interval”被再次聲明為值“0”和“undefined”,同時新的“refreshUp”function 被創建引用新的“計時器”和“間隔”。 當你釋放鼠標時,調用新的“refreshUp”,interval 和 timeout 不會被清除。
嘗試將計時器和間隔定義為 state 或使用“useRef”。 這樣它們就不會在重新渲染期間被重新定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.