我是 ReactJs 的新手,我正在尝试为 ipotetic 电子商务做一个简单的摘要篮:当您添加产品时,您需要知道它是否已经存在,在这种情况下仅增加商品编号。
正如你所看到的,如果该行不存在,我会执行一个连接(行它是一个对象
{
id: singleProd.id,
name: singleProd.name,
price: singleProd.price,
value: 1
}
),但如果存在,我只需要增加 value 属性
state = {
counters: []
};
addCounter = row => {
let countersRows = this.state.counters;
let existRow = countersRows.filter(c => c.id === row.id);
if (existRow.length !== 0) {
let index = countersRows.findIndex(x => x.id === existRow[0].id);
console.log("Update here... like this.state.counters[index].value + 1?");
} else {
this.setState({ counters: countersRows.concat(row) });
}
};
deleteRow = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters });
};
我听说过对象分配,但我不知道该怎么做。 非常感谢。
最佳答案
看起来您只是尝试增加具有匹配 ID 的第一个项目的 value 属性。如果是这样,这是您想要的吗?
addCounter = row => {
const { counters } = this.state;
const existingRow = counters.filter(c => c.id === row.id)[0];
if (existingRow.length !== 0) {
this.setState(
Object.assign(existingRow, { value: existingRow.value + 1 })
);
} else {
this.setState({ counters: counters.concat(row) });
}
};
关于arrays - 当状态是对象数组时如何更新特定值 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348793/