简体   繁体   English

当我使用 setstate 调用 function 时,State 值不会改变

[英]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.当单击(添加到列表)按钮时,将触发此 function。 but I have to click twice to change the state.` sorry for horrible English但我必须单击两次才能更改 state。抱歉英语很糟糕

react state changes are synchronous.反应 state 更改是同步的。

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.此外,您必须等到反应应用 state 更改后,才能在控制台语句中看到更改。

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: setState 是一个异步 function,它不会以异步方式设置状态,但稍后,您可以使用回调 function,如果您想在设置 Z9ED39E2EA931586B73A985A69EZEF 之后运行代码片段运行:

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 =>{
})

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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