我有一個重新發送代碼按鈕,按下后將禁用它 30 秒。這是我的功能。
const time = useRef(30);
function disableResendBtn() {
time.current = 30;
setsendCodeBtnDisabled(true);
const interval = setInterval(() => {
(time.current = time.current - 1),
setsendCodeBtnText(i18n.t('RESEND') '(' time.current ')'),
console.log(time.current);
}, 1000);
setTimeout(() => {
setsendCodeBtnDisabled(false);
setsendCodeBtnText(i18n.t('RESEND'));
clearInterval(interval);
}, 30000);
}
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function
當我轉到下一頁時出現錯誤。此錯誤并非每次都顯示。所以我很困惑是否是 setInterval/setTimeout 函式的原因。
無論如何,我如何使用 useEffect 來清理它?該函式不在 useEffect 中。
uj5u.com熱心網友回復:
您可以將setInterval
和setTimeout
的回傳值存盤在 ref 中,然后創建一個空值,useEffect
然后為您清理這些值。
我能想到一種更簡單的方法。無需跟蹤這些時間間隔和超時,然后使用空的 進行清理useEffect
,您只需創建一個useEffect
每秒更新一次當前時間的 。而且,要跟蹤禁用狀態,您可以創建另一個跟蹤“直到按鈕應該被禁用的時間”的狀態。
export default function App() {
const [currentTime, setCurrentTime] = React.useState(Date.now());
const [disabledUntil, setDisabledUntil] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
setCurrentTime(Date.now());
}, 1000);
return () => clearInterval(interval);
}, []);
const onClick = () => {
// disable button for 30 seconds
setDisabledUntil(Date.now() 30 * 1000);
};
const buttonDisabledSeconds = Math.floor(
(disabledUntil - currentTime) / 1000
);
return (
<div>
<button onClick={onClick} disabled={currentTime < disabledUntil}>
Send
</button>
<p>
{buttonDisabledSeconds >= 0 &&
`Button disabled for ${buttonDisabledSeconds} seconds`}
</p>
</div>
);
}
這樣,cleanup
非常接近實際的區間定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534852.html
下一篇:發布應用程式后如何更新持久資料?