直到第二个按钮按下后,值才会改变 [英] Value won't change until after the second button press

查看:42
本文介绍了直到第二个按钮按下后,值才会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以更改以增加对象值的按钮.

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");
},

我在同一ProgressBar中有两个值,因此当您添加一个值时,您需要取自另一个值.这就是为什么我要从托克尔拿走2.

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.

然后将其推送到Firebase后端:

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!

推荐答案

setState方法具有一个可选的第二个argumnet,它是在执行setState和调用render之后要执行的回调函数.

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]
)

在您的代码中,handleClick方法假定setState已执行并且值已更新.但是并不能保证总是如此.如果您提供handleCLick方法作为对setState的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);
}

这篇关于直到第二个按钮按下后,值才会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆