当前位置:网站首页>验证码倒计时自定义hooks
验证码倒计时自定义hooks
2022-08-10 19:13:00 【大风起兮云飞扬丶】
需要注意:虽然定时器中在不停的调用setTime改变time的值,但是在定时器中输出time的值是不会变的。因为函数式组件中每执行一次setState都会形成一个新的闭包,所以你改变的值只在你新的闭包中才能访问到。但是可使用useEffect+依赖的形式访问到这个值。
const useTimer = () => {
const [time, setTime] = useState();
const timeId = useRef(null);
const start = (count) => {
if (timeId.current) {
clearTimer();
}
setTime(count);
timeId.current = setInterval(() => {
setTime((t) => --t);
}, 1000);
};
const clearTimer = () => {
clearInterval(timeId.current);
};
useEffect(() => {
if (time <= 0) {
clearTimer();
}
}, [time]);
useEffect(() => clearTimer, []);
return {
time, start };
};
使用方法:
const {
time,start}= useTimer();
start(3)
边栏推荐
- Leetcode 200.岛屿数量 BFS
- Tf铁蛋白颗粒包载顺铂/奥沙利铂/阿霉素/甲氨蝶呤MTX/紫杉醇PTX等药物
- [Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
- 转铁蛋白Tf功能化β-榄香烯-雷公藤红素/紫杉醇PLGA纳米粒/雷公藤甲素脂质体(化学试剂)
- Introduction to 3 d games beginners essential 】 【 modeling knowledge
- Optimization is a habit The starting point is to 'stand close to the critical'
- @Autowired注解 --required a single bean, but 2 were found出现的原因以及解决方法
- 从 GAN 到 WGAN
- Random函数用法
- 你不知道的浏览器页面渲染机制
猜你喜欢

力扣18-四数之和——双指针法

铁蛋白颗粒Tf包载多肽/凝集素/细胞色素C/超氧化物歧化酶/多柔比星(定制服务)

laya打包发布apk

【C#】WCF和TCP消息通信练习,实现群聊功能

mysql踩坑----case when then用法

Apple Font Lookup

链表应用----约瑟夫问题
[email protected] nanomimetic e"/>Water-soluble alloy quantum dot nanozymes|CuMoS nanozymes|porous silicon-based Pt(Au) nanozymes|[email protected] nanomimetic e

leetcode 85.最大矩形 单调栈应用

网络虚拟化
随机推荐
爱丁堡大学最新《因果机器学习: 医疗健康与精准医疗应用》2022综述
1D Array Dynamics and Question Answers
史上最全GIS相关软件(CAD、FME、Arcgis、ArcgisPro)
苹果字体查找
血红素-金纳米颗粒(Heme-AuNP)复合纳米酶|金纳米颗粒核多孔空心碳纳米球壳([email protected])纳米酶
回老家去?
cordova installation error Command failed: powershell solution
(十二) findContours函数的hierarchy详解
The 2021 ICPC Asia Shanghai Regional Programming Contest D、E
3D Game Modeling Learning Route
子域名收集&Google搜索引擎语法
Ransom Letter Questions and Answers
(10) Sequence and deserialization of image data
flask生成路由的2种方式和反向生成url
Ferritin particle-loaded raltitrexed/pemetrexed/sulfadesoxine/adamantane (scientific research reagent)
优化是一种习惯●出发点是'站在靠近临界'的地方
多线程与高并发(五)—— 源码解析 ReentrantLock
servlet映射路径匹配解析
leetcode 85.最大矩形 单调栈应用
QoS Quality of Service Seven Switch Congestion Management