javascript - 递减计数器有奇怪的行为
问题描述
我正在用 setInterval 建立一个计数器,它每秒减少时间,在最初的几秒钟内工作,然后卡住并同时增加和减少。
在我的情况下,我从 5:00 (m:ss) 开始,几秒钟后在 4:49 左右停止,然后开始增加然后减少......
不知道发生了什么。
start = () => {
console.log('starting')
let timeLeft = this.state.totalDuration
setInterval(() => {
if (timeLeft > 0) {
timeLeft = (timeLeft - 1000)
this.setState({ totalDuration: timeLeft })
}
}, 1000)
}
render() {
return (
<View style={styles.container}>
<Timer interval={this.state.totalDuration}></Timer>
<ButtonsRow>
<RoundButton title='Reset' color='white' background='grey'></RoundButton>
<RoundButton onPress={this.start()} title='Start' color='white' background='red'></RoundButton>
</ButtonsRow>
</View>
解决方案
您正在timeLeft
区间函数之外的闭包中捕获变量。因此,它在按下开始时被捕获一次,之后保持相同的值。而是使用setState
接受回调的变体。
start = () => {
console.log('starting')
const interval = setInterval(() => {
this.setState(state => {
if (state.totalDuration > 0)
return { totalDuration : state.totalDuration - 1000 }
else {
clearInterval(interval)
return {}
}
})
}, 1000)
}
推荐阅读
- java - 此代码如何导致填充 dummy 和 L3 列表?
- angular - 如何过滤来自商店的对象数组(通过选择器)
- python - 即时更新 KivyMD 按钮(Python)
- typescript - 如何使用 TypeScript 在 express 中键入`request.query`?
- nvidia - 尝试将其转换为 tensorrt 或 tflite 时出现内存问题
- sql - 基于条件结束的 SAS 宏循环
- mysql - Django order_by 导致查询非常慢
- primes - 素数的乘积
- vue.js - 如何在页面刷新时更新 vue-router?
- java - 在本地机器上克隆 JUnit 5 后,执行“assemble”任务时出现编译时错误