3 回答
![?](http://img1.sycdn.imooc.com/5333a0780001a6e702200220-100-100.jpg)
TA贡献1810条经验 获得超4个赞
你快到了。@Clarity 提供了很好的解决方案。如果您想替换现有值并用新值替换它
尝试这个
handleChange = (label, uniqueId) => {
const { selectedItems } = this.state
// Find items that already exists in array
const findExistingItem = selectedItems.find((item) => {
return item.uniqueId === uniqueId;
})
if(findExistingItem) {
// Remove found Item
selectedItems.splice(findExistingItem);
// set the state with new values/object
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
} else {
// if new Item is being added
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
}
};
![?](http://img1.sycdn.imooc.com/54585094000184e602200220-100-100.jpg)
TA贡献1854条经验 获得超8个赞
你可以这样做:
handleChange = (label, uniqueId) => {
this.setState(state => ({ selectedItems: [...state.selectedItems, uniqueId]}));
};
通过使用数组展开和函数形式,setState确保您不会直接改变状态并将项目添加到最新状态。
如果你想用一label: uniqueId对添加一个对象,你可以这样做:
handleChange = (label, uniqueId) => {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
[label]: uniqueId
}]
}));
};
编辑:如果要覆盖具有相同标签的项目,最简单的方法是将它们存储为对象而不是数组,因此具有相同标签的项目将覆盖现有项目:
handleChange = (label, uniqueId) => {
this.setState(state => {
return { selectedItems: { ...state.selectedItems, [label]: uniqueId } };
});
};
![?](http://img1.sycdn.imooc.com/545845b40001de9902200220-100-100.jpg)
TA贡献1841条经验 获得超3个赞
老实说,我不明白,你想做什么,但如果你需要在数组中添加对象(或其他东西),你可以使用.push()方法。例如:
let addToArray = [];
let test = {"label": "ageRange", "uniquId": 2};
addToArray.push(test);
console.log(addToArray); //[{label: "ageRange", uniquId: 2}]
添加回答
举报