简体   繁体   English

如何反应更新状态?

[英]How does react update state?

I'm getting a very strange issue that I don't know how to address. 我遇到了一个非常奇怪的问题,我不知道该如何解决。

I've got a fairly straightforward method: When a button is pressed it called toggleInverted() 我有一个相当简单的方法:按下按钮时,它名为toggleInverted()

toggleInverted() {
  if(this.state.inverted){
    this.setState({inverted: false});
  } else{
    console.log("got to else...");
    this.setState({inverted: true});
    console.log(this.state.inverted);
  }
}

The inverted field is initialized in the constructor to false . 反向字段在构造函数中初始化为false However the first time I click the button when I load the page, it doesn't correctly reset the state. 但是,当我第一次加载页面时单击该按钮时,它无法正确重置状态。 The output is: got to else... false . 输出为: got to else... false

So somehow it is getting into this else statement, executing the setState , and yet not setting inverted to be true... 所以以某种方式进入了else语句,执行了setState ,但是没有将倒置设置为true。

Is there something about setState that I am missing? 我缺少关于setState东西吗?

setState may be asynchronous setState 可能是异步的

Meaning you cannot expect the values of this.state to change immediately after setState is called. 这意味着在调用setState之后,您不能期望this.state的值立即更改。

To quote the docs : 引用文档

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即使this.state发生突变,但会创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value... 调用此方法后访问this.state可能会返回现有值...


As an aside, you can figure your code by using the negative expression of the current inverted value as follows: 顺便说一句,您可以通过使用当前反转值的负表达式来计算代码,如下所示:

toggleInverted() {
  this.setState({inverted: !this.state.inverted});
}

setState does not change your components state immediately. setState不会立即更改组件状态。 Your state change may be asynchronous and thus no guarantee that your console.log statement will print the changed state. 您的状态更改可能是异步的,因此不能保证console.log语句将打印更改后的状态。 setState however does always lead to the render method being called, so if you console log your state inside the render method of your component, your state should be true. 但是setState始终会导致调用render方法,因此,如果您在组件的render方法内控制台记录状态,则状态应该为true。

Also, this.setState({inverted: !this.state.inverted}) is a shorter version of your code snippit 另外, this.setState({inverted: !this.state.inverted})是代码段的较短版本

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

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