当页面跳转时,定时器无法停止
来源:1-1 课程导学
蓝色西西
2021-10-06
DELL老师,下面的nextjs代码。为什么当input type='password’时。页面启动的定时器,在页面跳转时,无法在控制台中停止。必须要input type=‘text’ 才可以。怎么做,才能让定时器在页面跳转时,停止。
import { useRouter } from ‘next/router’;
import React, { useState,useEffect } from ‘react’
function timer(){
const router = useRouter();
const [captchaButtonDisabled,setCaptchaButtonDisabled] = useState(false)
const [captchaText,setCaptchaText] = useState('获取验证码')
const [timeCount,setTimeCount] = useState(20)
let defaultCaptcha = captchaText
let left = '还剩';
let seconds = '秒';
let timer = null;
useEffect(() => {
console.log('mount')
return () => {
// location.reload()
setTimeCount(0)
clearInterval(timer)
console.log('unmount')
}
}, [])
let iCount = timeCount;
let startTimer = () => setInterval(() => {
if ( timeCount>0 && iCount > 0 ) {
let text = left + ' ' + iCount + ' ' + seconds;
setCaptchaText(text)
iCount --;
console.log(iCount)
} else {
clearInterval(timer); // 清除定时器
setCaptchaText(defaultCaptcha)
setCaptchaButtonDisabled(false)
}
}, 1000);
//获取验证码
function getCaptcha(event) {
if (captchaButtonDisabled){
return;
}
setCaptchaButtonDisabled(true)
//验证码倒计时
if (!timer) {
timer = startTimer()
}
else {
setCaptchaButtonDisabled(false)
}
}
async function pagePush(){
router.push('/')
}
return (
<input name="email" type="text"/>
<input name="password" type="password" />
<button type="button" disabled={captchaButtonDisabled} onClick={()=>getCaptcha()}>{captchaText}</button>
<button type="button" onClick={pagePush}>点击页面跳转,测试查看控制台 验证码定时器 是否在unmount中被清除</button>
</div>
)
}
export default timer;
写回答
1回答
-
Dell
2021-10-06
你这个很可能是timer 反复创建,导致最后销毁无法找到引用造成的
042021-10-17
相似问题