当前位置:网站首页>验证码倒计时自定义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)
边栏推荐
- Public Key Retrieval is not allowed(不允许公钥检索)【解决办法】
- Colocate Join :ClickHouse的一种高性能分布式join查询模型
- What is the upstream bandwidth and downstream bandwidth of the server?
- 《分布式微服务电商》专题(一)-项目简介
- Redis persistence mechanism
- (十二) findContours函数的hierarchy详解
- Hangdian Multi-School Seven 1003-Counting Stickmen (Combination Mathematics)
- The 2021 ICPC Asia Shanghai Regional Programming Contest D、E
- 【二叉树】二叉搜索树的后序遍历序列
- Optimization is a habit The starting point is to 'stand close to the critical'
猜你喜欢
whois information collection & corporate filing information
@Autowired注解 --required a single bean, but 2 were found出现的原因以及解决方法
[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
电脑如何去掉u盘写保护的状态
Solution for thread not gc-safe when Rider debugs ASP.NET Core
基于TCP的聊天系统
导入FontForge生成字体
idea插件 协议 。。 公司申请软件用
铁蛋白颗粒负载雷替曲塞/培美曲塞/磺胺地索辛/金刚烷(科研试剂)
(十二) findContours函数的hierarchy详解
随机推荐
皮质-皮质网络的多尺度交流
「POJ 3666」Making the Grade 题解(两种做法)
echart 特例-多分组X轴
【SemiDrive源码分析】【MailBox核间通信】52 - DCF Notify 实现原理分析 及 代码实战
@Autowired annotation --required a single bean, but 2 were found causes and solutions
七月券商金工精选
idea插件 协议 。。 公司申请软件用
UnitTest中的Path must be within the project 问题
Heme - gold nanoparticles (Heme - AuNP) composite nanometer enzyme | gold nanoparticles nuclear porous hollow carbon nanometer spherical shell (Au @ HCNs) nano enzyme
nfs挂载服务器,解决挂载后无法更改用户id,无法修改、写文件,文件只读权限Read-only file system等问题
转铁蛋白Tf功能化β-榄香烯-雷公藤红素/紫杉醇PLGA纳米粒/雷公藤甲素脂质体(化学试剂)
laya打包发布apk
【luogu CF1534F2】Falling Sand (Hard Version)(性质)(dfs)(线段树 / 单调队列 / 贪心)
烟雾、空气质量、温湿度…自己徒手做个环境检测设备
MATLAB设计,FPGA实现,联合ISE和Modelsim仿真的FIR滤波器设计
导入FontForge生成字体
keepalived:故障检测自动修复脚本
电脑为什么会蓝屏的原因
端口探测详解
1D Array Dynamics and Question Answers