简体   繁体   中英

State value doesn't change when I call a function with setstate

addTOList= (id) =>{
  const movieId = id
  const movie = movies.find( ({ id }) => id === movieId );
  const stateMovie = [...this.state.movie, movie]
  console.log(stateMovie)
  this.setState({
    movie : stateMovie
  })
  console.log(this.state.movie)
  localStorage.setItem('movies', JSON.stringify(this.state.movie))
  this.state.movie.map(mov =>{
  })
}

This function will be triggered when the (Add to list) button is clicked. but I have to click twice to change the state.` sorry for horrible English

react state changes are synchronous.

Check this question & answer here

If your 'next state' depends on the 'previous state' then you should use this pattern:

  this.setState(prev => ({
    ...prev,
    movie : [...prev.movie, movie],
  }))

Also you must wait until the state change has been applied by react before you will see the changes in your console statement.

setState is an async function, it do not setstate in async manner but later, you can use a callback function, if you want to run a code snippet after set state is run:

addTOList = () => { this.setState({ movie: stateMovie }, () => { console.log(this.state.movie) }) }

again myself, I did some change and this worked but I no Idea this is the right way to do or not

addTOList= (id) =>{
const movieId = id
const movie = movies.find( ({ id }) => id === movieId );
const stateMovie = [...this.state.movie, movie]
console.log(stateMovie)
this.state.movie = stateMovie
this.setState({})

console.log(this.state.movie)
localStorage.setItem('movies', JSON.stringify(this.state.movie))
this.state.movie.map(mov =>{
})

}

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