当前位置:网站首页>验证码倒计时自定义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)
边栏推荐
- 铱钌合金/氧化铱仿生纳米酶|钯纳米酶|GMP-Pd纳米酶|金钯复合纳米酶|三元金属Pd-M-Ir纳米酶|中空金铂合金纳米笼核-多空二氧化硅壳纳米酶
- Optimization is a habit The starting point is to 'stand close to the critical'
- 从 Delta 2.0 开始聊聊我们需要怎样的数据湖
- Pt/CeO2单原子纳米酶|[email protected] NPs纳米酶|碳纳米管负载铂颗粒纳米酶|白血病拮抗多肽修饰的FeOPtPEG复合纳米酶
- 2020 ICPC Shanghai Site G
- 『牛客|每日一题』岛屿数量
- YOLOv3 SPP source analysis
- 代理模式的使用总结
- spark学习笔记(九)——sparkSQL核心编程-DataFrame/DataSet/DF、DS、RDD三者之间的转换关系
- 【二叉树】二叉搜索树的后序遍历序列
猜你喜欢
Multifunctional Nanozyme Ag/PANI | Flexible Substrate Nano ZnO Enzyme | Rhodium Sheet Nanozyme | Ag-Rh Alloy Nanoparticle Nanozyme | Iridium Ruthenium Alloy/Iridium Oxide Biomimetic Nanozyme
QoS Quality of Service Six Router Congestion Management
测试/开发程序员值这么多钱么?“我“不会愿赌服输......
转铁蛋白(TF)修饰紫杉醇(PTX)脂质体(TF-PTX-LP)|转铁蛋白(Tf)修饰姜黄素脂质体
Heme - gold nanoparticles (Heme - AuNP) composite nanometer enzyme | gold nanoparticles nuclear porous hollow carbon nanometer spherical shell (Au @ HCNs) nano enzyme
巧用RoaringBitMap处理海量数据内存diff问题
Apache DolphinScheduler 3.0.0 正式版发布!
UE4 - 河流流体插件Fluid Flux
【毕业设计】基于STM32的天气预报盒子 - 嵌入式 单片机 物联网
Tf铁蛋白颗粒包载顺铂/奥沙利铂/阿霉素/甲氨蝶呤MTX/紫杉醇PTX等药物
随机推荐
《分布式微服务电商》专题(一)-项目简介
(10) Sequence and deserialization of image data
argparse——命令行参数解析
常见端口及服务
Iridium Ruthenium Alloy/Iridium Oxide Biomimetic Nanozyme | Palladium Nanozyme | GMP-Pd Nanozyme | Gold-Palladium Composite Nanozyme | Ternary Metal Pd-M-Ir Nanozyme |shell nanozyme
哈工大软件构造Lab3(2022)
[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
【二叉树】二叉搜索树的后序遍历序列
杭电多校七 1003-Counting Stickmen(组合数学)
多线程与高并发(五)—— 源码解析 ReentrantLock
FEMRL: A Framework for Large-Scale Privacy-Preserving Linkage of Patients’ Electronic Health Rec论文总结
(12) findContours function hierarchy explanation
opengrok搭建[通俗易懂]
spark学习笔记(九)——sparkSQL核心编程-DataFrame/DataSet/DF、DS、RDD三者之间的转换关系
【greenDao】Cannot access ‘org.greenrobot.greendao.AbstractDaoSession‘ which is a supertype of
Linux服务器安装Redis,详细步骤。
WCF and TCP message communication practice, c # 】 【 realize group chat function
QoS Quality of Service Eight Congestion Avoidance
@Autowired annotation --required a single bean, but 2 were found causes and solutions
【毕业设计】基于STM32的天气预报盒子 - 嵌入式 单片机 物联网