Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - 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
    })
  }
question from:https://stackoverflow.com/questions/65648054/react-function-doesnt-update-state

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change this

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

to:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...