简体   繁体   English

反应setState的正确用法

[英]React setState proper usage

So I read a lot that setState calls are batched and are async, and that one should use the updater function to update state when any value is read from the state in setState . 因此,我了解到很多内容,即setState调用是批处理的并且是异步的,并且当从setState的状态读取任何值时,应该使用updater函数来更新状态。

class App extends React.Component {
  state = { count: 1 }
  handleClick = () => {
    this.setState({ count: this.state.count + 1 }) 
  }

  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <button onClick={this.handleClick}>Click</button>
      </div>
    )
  }
}

Considering above code ONLY, can someone explain what might go wrong in this case by not using the updater pattern of setState ? 仅考虑上述代码,有人可以通过不使用setState的更新程序模式来解释在这种情况下可能出什么问题吗? Even if setState is called later, this.state will always refer to previous state, which is what we want here. 即使稍后调用setStatethis.state也将始终引用先前的状态,这就是我们在这里想要的。

PS: I know that calling setState multiple times one after the other will cause errors in this kind of scenario because they are async, but that's not the case here. PS:我知道一个接setState多次调用setState会在这种情况下导致错误,因为它们是异步的,但是这里不是这种情况。

One reason that you should not do this is setStates async behavior. 不应执行此操作的一个原因是setStates异步行为。 for example if you had two setStates in a single function you wont get the desired output. 例如,如果在一个函数中有两个setState,则不会获得所需的输出。 consider this: 考虑一下:

handleClick(){
    this.setState({
        count : this.state.count + 1
    })
    this.setState({
        count : this.state.count + 1
    })
}

If you log the this.state.count now its value will be incremented only by one, but if you do it like this: 如果您现在记录this.state.count其值将仅增加一,但是如果您这样做,则:

handleClick(){
    this.setState((prevState)=>({
        amount : prevState.count + 1
    }))
    this.setState((prevState)=>({
        amount : prevState.count + 1
    }))
}

you will get correct output. 您将获得正确的输出。

also

the DOM is not updated as soon as setState is invoked. 调用setState时不会立即更新DOM。 Rather, React batches multiple updates into one update and then renders the DOM. 相反,React将多个更新批处理为一个更新,然后呈现DOM。 You may receive outdated values while querying the state object How to NOT React 而查询状态对象,可能会收到过时的价值观如何不反应

EDIT : i just saw the last paragraph of your question and seems like my answer is exactly what you said you already know! 编辑 :我刚刚看到了您问题的最后一段,似乎我的回答正是您所说的,已经知道了! well in that case i think its just respecting the good practices. 在那种情况下,我认为它只是尊重良好做法。

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

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