reactjs 如何在React中停止setInterval()

cwdobuhd  于 2022-12-29  发布在  React
关注(0)|答案(2)|浏览(210)

我使用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请求仍在发送

yk9xbfzb

yk9xbfzb1#

您正在覆盖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)
        }
bxjv4tth

bxjv4tth2#

我通过添加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()
  }

相关问题