简体   繁体   English

将新数组动态添加到现有 object 数组 React JS

[英]Dynamically add new array to existing object array React JS

I am getting the value of id and quantity during the click button.在单击按钮期间,我得到了 id 和数量的值。 I want add a new array inside the object array.我想在 object 数组中添加一个新数组。 Below is the code下面是代码

adddata =(d,v) => {

    const product = [];

    for (let i = 0; i < 1; i++) {

    product.push({
                   product_id:d,    
                   cart_quantity:v
            });
        }
console.log(product);


<button value={this.state.quantity} className="btn" onClick={adddata} data-id={item.product_id}>Add to cart</button>

The only issue with this implementation is that.这个实现的唯一问题是。 it replacing the new value with an existing one.它将新值替换为现有值。 I want to merge it dynamically every time click on the button.我想在每次点击按钮时动态合并它。

Please help请帮忙

You defined the variable product inside the function, So each time when you execute the function, It will be reinitialized.你在function里面定义了变量product ,所以每次执行function的时候,都会重新初始化。

Use Global Variable / State使用全局变量/State

// global
const product = [];

addData =(d,v) => {

    // I removed the loop because it's useless here.

    product.push({
       product_id:d,    
       cart_quantity:v
    });
}

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

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