问题描述
做一个验证码发送倒计时的组件,其倒数逻辑如下:
const [time,setTime]=useState(60)
// ....
const send = () => {
timer = setInterval(() => {
if (seconds > 1) {
setTime(time-1)
} else {
clearInterval(timer);
setTime(60)
timer = null;
}
}, 1000);
};
写完运行发现,一直都显示59.这里是由于闭包,,setTime并不会立即把time值更新,所以就相当于
const [time,setTime]=useState(60)
// ....
const send = () => {
timer = setInterval(() => {
if (time> 1) {
setTime(60-1)
} else {
clearInterval(timer);
setTime(60)
timer = null;
}
}, 1000);
};
解决方案
let seconds;
const send = () => {
if (!status) {
sendCode();
setStatus(1);
timer = setInterval(() => {
if (seconds > 1) {
seconds--;
} else {
clearInterval(timer);
seconds = timespan;
setStatus(0);
timer = null;
}
setTime(seconds); // 注意这里
}, 1000);
}
};
让setTime
保持对一个可以同步更新的变量的引用即可