Value won't change until after the second button press

ε祈祈猫儿з 提交于 2019-12-25 11:34:41

问题


I have a button that changes increases the value of an object.

<Button bsStyle="info" bsSize="lg" onClick={this.addKoala}>

addKoala:

addKoala: function() {
  this.setState({
    towelCount: this.state.towelCount - 2,
    koalaCount: this.state.koalaCount + 2
  });
  this.handleClick("Koala");
},

I have two values that are in the same ProgressBar, so when you add to one, you need to take from another. That's why I'm taking 2 away from tokel.

it then goes here to be pushed to a firebase backend:

handleClick: function(itemAdded) {
  var style = null;
  if (itemAdded === "Towel") {
    style = "danger"
  } else {
    style = "info"
  }
  this.props.itemsStore.push({
    itemStyle: style,
    text: "A new " + itemAdded + " was rewarded!",
    curItemCount: "It's now: " + this.state.towelCount + " to " + this.state.koalaCount,
  });

  var submitJSON = {
    "koalaCount": this.state.koalaCount,
    "towelCount": this.state.towelCount
  };
  Actions.patchScores(submitJSON);
},

After I refresh the website, the first time I press the button everything works but the values of koala and towel don't change. After that, it works done, but that first time isn't working. Any help would be greatly appreciated!


回答1:


The setState method has an optional 2nd argumnet that is a callback function to be executed after the setState has been executed and render was called.

void setState(
  function|object nextState,
  [function callback]
)

In your code you handleClick method assumes that setState has been executed and the valaues updated. But there is no guarantee that this is always true. If you provide your handleCLick method as the callBack to setState this can be ensured.

addKoala: function() {
  this.setState({
    towelCount: this.state.towelCount - 2,
    koalaCount: this.state.koalaCount + 2
  },  this.handleClick("Koala").bind(this);
}


来源:https://stackoverflow.com/questions/35735229/value-wont-change-until-after-the-second-button-press

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!