背景
我是在 react 的函数组件中遇到这个问题的,
出现问题的代码片段:
const SelfDevProgress = (props)=> {
const [getChangePer,setGetChangePer] = useState(percent)
let timer = null; // 定时器
// 调起进度条
const initial = () => {
// 进度条步数
let per = 0
setGetChangePer(per)
timer = setInterval(() => {
per += s
if(per === 99) { // 在100之前要卡住停顿
clearInterval(timer)
}
if(per + s >= 100) { // 最后一段改变步幅
s = 1
}
setGetChangePer(per)
}, 100);
}
// 响应失败
const fail = () => {
// 清除定时器
clearInterval(timer) // 这里调用clearInterval了,但是定时器仍在运行
}
}
在 fail() 函数中调用 clearInterval
来清除定时器了, 但是发现定时器还在运行.
解决办法
把 timer 改成 useState 那种方式就可以了.
const [timer,setTimer] = useState(null) // 定时器
// 调起进度条
const initial = async () => {
// 进度条步数
let per = 0
setGetChangePer(per)
let t = setInterval(() => {
per += s
if(per === 99) { // 在100之前要卡住停顿
clearInterval(t)
}
if(per + s >= 100) { // 最后一段改变步幅
s = 1
}
setGetChangePer(per)
}, 100);
setTimer(t)
}