[英]How to stop setInterval() in React
我使用 setInterval() 发送 state 更新的 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 请求继续发送
您正在覆盖您的componentDidUpdate
调用中的当前间隔。 做一个检查,例如
if (this.state.isSyncStart) {
this.interValID == 0 && this.getSynProcessState() //setInterval()
console.log('componentDidUpdate: ' + this.state.isSyncStart)
} else {
clearInterval(this.intervalID)
console.log('componentDidUpdate: ' + this.state.isSyncStart)
}
我通过添加 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() }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.