当input type='password'时,定时器无法停止

来源:1-1 课程导学

蓝色西西

2021-10-06

老师,下面的代码,为什么当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回答

Jokcy

2021-10-07

无法在控制台中停止?是什么概念,你具体的操作是什么?

0
3
Jokcy
另外你这个写法有问题,你应该把timer放到`useEffect`的依赖中,不然你的timer更新useEffect不知道的
2021-10-13
共3条回复

全栈进阶课程 React16.8+Next.js+Koa2一步到位开发Github

学习React/Next.js服务端渲染SSR同构设计方案,理解OAuth登录体系的实现原理

651 学习 · 311 问题

查看课程