最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reactjs add a number to a state? - Stack Overflow

programmeradmin0浏览0评论

say I had a Reactjs state that was organized like so:

getInitialState: function(){
return {food: ''}
}

How would I add conditional number values to that state? Say something like:

firstset: function(){
this.setState({food: +9});
}

And

secondset:function(){
this.setState({food: +10});
}

I would like to know how I would go about iterating these numbers to the state of 'food' when the firstset function is activated, along with the secondset. So the consequence of activating them both once is 9+10, which would make food: 19.

say I had a Reactjs state that was organized like so:

getInitialState: function(){
return {food: ''}
}

How would I add conditional number values to that state? Say something like:

firstset: function(){
this.setState({food: +9});
}

And

secondset:function(){
this.setState({food: +10});
}

I would like to know how I would go about iterating these numbers to the state of 'food' when the firstset function is activated, along with the secondset. So the consequence of activating them both once is 9+10, which would make food: 19.

Share Improve this question asked Aug 4, 2016 at 0:50 Jason ChenJason Chen 2,5876 gold badges27 silver badges47 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You can refer to the previous state while setting it:

getInitialState: function() {
  return {
    food: 0
  }
}

firstSet: function() {
  this.setState({
    food: this.state.food + 9
  })
}

secondSet: function() {
  this.setState({
    food: this.state.food + 10
  })
}

First of all, food should be initially set as Number:

getInitialState: function(){
  return {
    food: 0
  }
}

Then to add some value to something you need the value.. so just take the this.state.food value..

incBy: function(value) {
   this.setState({
     food: this.state.food + value
   });
}
发布评论

评论列表(0)

  1. 暂无评论