老师,下面的代码,为什么当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;
学习React/Next.js服务端渲染SSR同构设计方案,理解OAuth登录体系的实现原理
了解课程