3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
你快到了。@Clarity 提供了很好的解決方案。如果您想替換現(xiàn)有值并用新值替換它
嘗試這個(gè)
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
}]
}))
}
};

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
你可以這樣做:
handleChange = (label, uniqueId) => {
this.setState(state => ({ selectedItems: [...state.selectedItems, uniqueId]}));
};
通過(guò)使用數(shù)組展開(kāi)和函數(shù)形式,setState確保您不會(huì)直接改變狀態(tài)并將項(xiàng)目添加到最新?tīng)顟B(tài)。
如果你想用一label: uniqueId對(duì)添加一個(gè)對(duì)象,你可以這樣做:
handleChange = (label, uniqueId) => {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
[label]: uniqueId
}]
}));
};
編輯:如果要覆蓋具有相同標(biāo)簽的項(xiàng)目,最簡(jiǎn)單的方法是將它們存儲(chǔ)為對(duì)象而不是數(shù)組,因此具有相同標(biāo)簽的項(xiàng)目將覆蓋現(xiàn)有項(xiàng)目:
handleChange = (label, uniqueId) => {
this.setState(state => {
return { selectedItems: { ...state.selectedItems, [label]: uniqueId } };
});
};

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
老實(shí)說(shuō),我不明白,你想做什么,但如果你需要在數(shù)組中添加對(duì)象(或其他東西),你可以使用.push()方法。例如:
let addToArray = [];
let test = {"label": "ageRange", "uniquId": 2};
addToArray.push(test);
console.log(addToArray); //[{label: "ageRange", uniquId: 2}]
添加回答
舉報(bào)