简体   繁体   中英

React setState is not working correctly

I am creating a slider using ReactJS.

I used componentDidMount() to start slider from slide 0, every 2 seconds (Using setInterval() function). It works fine by changing slide number via setState() method.

I have created two buttons to force slider to move left or right by clicking on. Also, I have written a method for onClick() to increase or decrease the slide number.

Once, I have clicked on one of them, it works fine, and the state changes successfully. However, this rendering will be reset to previous state before clicking!

For an example, if I am in slide 2 and hit on left button I should expect slide 1 is shown and it is Ok. However, after 2 seconds it returns to slide 3 instead of 2.

What's wrong with this?

state = {
  activeSlideNumber: 0,
}

//Total Number of items is 5

sliderLeft = () => {
  let leftnumber = 0
  let newActiveSlideNumber = this.state.activeSlideNumber
  newActiveSlideNumber === 0 ? leftnumber = 4 :  leftnumber = newActiveSlideNumber - 1 
  this.setState({
    activeSlideNumber: leftnumber
  })
}

componentDidMount() {
  let newActiveSlideNumber = this.state.activeSlideNumber
  setInterval(() => {
    newActiveSlideNumber === 4 ? newActiveSlideNumber = 0 : newActiveSlideNumber++
    this.setState({
      activeSlideNumber: newActiveSlideNumber
    })
  }, 2000)
}

Only when the component gets mounted, newActiveSlideNumber is taking the value from the state. After every 2 sec its not taking the updated value from the state because the statement let newActiveSlideNumber = this.state.activeSlideNumber is outside the setinterval function.

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