javascript - 如何在 React 中停止 setInterval()
问题描述
我使用 setInterval() 发送 GET 请求以进行状态更新。更新过程完成后,我也使用 clearInterval() 。
//
// getSynProcessState used for updating data by sending GET request to an API after every minute
//
intervalID = 0;
getSynProcessState = () => {
// get total and current sync
this.intervalID = setInterval(() => {
axios.get('http://mySite/data/')
.then(res => {
console.log(res.data)
});
},1000);
}
//
// clearInterval() will run if this.state.isSyncStart === false
//
componentDidUpdate() {
if (this.state.isSyncStart) {
this.getSynProcessState() //setInterval()
console.log('componentDidUpdate: ' + this.state.isSyncStart)
} else {
clearInterval(this.intervalID)
console.log('componentDidUpdate: ' + this.state.isSyncStart)
}
}
如您所见,当 [this.state.isSyncStart === true] => setInterval() 运行正常但是当 [this.state.isSyncStart === false] => clearInterval() 运行但 GET 请求继续发送
解决方案
我通过添加 runOnce 并将其设置为“如果”条件以某种方式解决了该问题。也许它可以防止覆盖 [this.intervalID]
runOnce = true
getSynProcessState = () => {
if (this.state.isSyncStart && this.runOnce) {
this.runOnce = false
this.intervalID = setInterval(() => {
axios.get('http://192.168.51.28:8031/process/')
.then(res => {
console.log(res.data)
// this.setState({
// total: res.data.total,
// current: res.data.current
// })
// console.log('1: ' +this.state.total)
});
},200);
} else {
clearInterval(this.intervalID)
}
}
componentDidUpdate() {
this.getSynProcessState()
}
推荐阅读
- powerbi - 电源查询(powerbi)数据结构:创建横截面-时间数据结构(面板数据)
- python - 在 Python 中绘制 3D 矢量场
- spring - 18+) 错误:405 不支持请求方法“GET”
- mysql - 在比较运算符中更改操作数顺序时出现 MySQL 错误
- android - Android Studio Arctic Fox 更新后构建失败,gradlew 签名报告有错误
- android - 与 com.google.android.youtube.player.YouTubePlayerSupportFragment 的另一个片段重复的 ID、标签 null 或父 ID
- sql - 选择每组列中的最大值
- python - 如何在python中找到函数的傅里叶变换幅度?
- hadoop - 创建表时将字符串转换为配置单元中的时间戳
- php - Laravel 5.8:加载图像无法正常工作