如何在React中停止setInterval()

问题描述 投票:0回答:2

我使用 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() 运行 OK 但是当 [this.state.isSyncStart === false] =>clearInterval() 运行但 GET 请求继续发送时

javascript reactjs asynchronous setinterval clearinterval
2个回答
0
投票

您正在覆盖

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)
        }

0
投票

我通过添加 runOnce 并将其设置在“If”条件中以某种方式解决了问题。也许它可以防止覆盖 [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()
  }

© www.soinside.com 2019 - 2024. All rights reserved.