简体   繁体   中英

React function doesn't update state

I would like at the start of startStop(), "secs" would equal "remaining". then set state "remaining" to equal "secs" at the end of the interval. However, the "secs" does update each 1000 millisecond, but setState for "remaining" does not actually update. Does it has to do anything with secs only update within the nested function decrement()? How to get "remaining" to update?

class App extends Component {
  state = {
    timerState: "paused"
    remaining: 1500,
  }

startStop() {
    
    var secs = this.state.remaining

    function getminutes()  
      return Math.floor(secs / 60)
    }

    function getseconds() { 
      return secs - Math.round(getminutes() * 60)
    } 

    function appendZero(number) {
      if (number <= 9)
        return "0" + number
      else
        return number
    }

    const decrement = () => {
        document.getElementById("minutes").innerHTML = appendZero(getminutes())
        document.getElementById("seconds").innerHTML = appendZero(getseconds())
        secs = secs - 1
    }

    if (this.state.timerState === "paused") {
      this.setState({
        timerState: setInterval(() => decrement(), 1000)
      }, 
      this.setState({
        remaining: secs
      })
    }
    
    else if (this.state.timerState !== "paused") {
      clearInterval(this.state.timerState)
      this.setState({
        timerState: "paused"
      })
    }

    this.setState({
      remaining: secs
    })
  }

Change this

   this.setState({
            timerState: setInterval(() => decrement(), 1000)
          }, 
          this.setState({
            remaining: secs
          })

to:

this.setState({
        timerState: setInterval(() => decrement(), 1000),
        remaining: secs
      })

Got it to work. I moved the setState to increment() as below:

const decrement = () => {
        document.getElementById("minutes").innerHTML = appendZero(getminutes())
        document.getElementById("seconds").innerHTML = appendZero(getseconds())
        secs = secs - 1
        this.setState({
          remaining: secs
        })
    }

Still don't understand why it doesn't work if setState() at the end of startStop() as my original question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM