Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新react中数组的嵌套对象中的值_Javascript_Reactjs - Fatal编程技术网

Javascript 更新react中数组的嵌套对象中的值

Javascript 更新react中数组的嵌套对象中的值,javascript,reactjs,Javascript,Reactjs,我和国家一起工作,但我有点被国家的价值所束缚 state= { ingredients: [ {Cheese: 0}, {Bacon: 0} ] } <button onClick={this.add}>ADD</button> 状态={ 成分:[ {Cheese:0}, {Bacon:0} ] } 添加 我想在单击按钮时将Cheese的值更改为1 我找不到解决方案您的this.a

我和国家一起工作,但我有点被国家的价值所束缚

state= {
        ingredients: [
            {Cheese: 0},
            {Bacon: 0}
        ]
    }
<button onClick={this.add}>ADD</button>
状态={
成分:[
{Cheese:0},
{Bacon:0}
]
}
添加
我想在单击按钮时将Cheese的值更改为1
我找不到解决方案

您的this.add函数是什么样子的?它绑定正确吗?add=()=>{this.setState({配料:this.state.components[0].Cheese+1})请用代码提问。@Aziz,这不正确,它将使state=
{components:1}
 add = () => {
    this.setState(prevState => {
      const ingredients = prevState.ingredients.map(ing => {
        if (ing["Cheese"]) {
          return { ...ing, Cheese: ing["Cheese"] + 1 };
        }
        return ing;
      });
      return {
        ingredients
      };
    });
  };