我保存在國家項目的集合:如何在React中有條件地更新集合中項目的屬性?
this.state = {
items: [
{ name: "foo", description: "a foo", index: 0 },
{ name: "bar", description: "a bar", index: 1 },
{ name: "herp", description: "a herp", index: 2 },
{ name: "derp", description: "a derp", index: 3 }
]
};
的index
屬性表示每個項目的集合中的順序位置。在某些時候,我需要重新訂購這些物品。例如,「DERP」可能需要移動到前面,所以其他項目的索引需要更新:
{ name: "derp", description: "a derp", index: 0 },
{ name: "bar", description: "a bar", index: 1 },
{ name: "herp", description: "a herp", index: 2 },
{ name: "foo", description: "a foo", index: 3 }
我目前使用的更新從update
的immutability-helper
包的狀態。不過,我確信這不是正確的方法(雖然它的工作原理):
// originalIndex is a variable holding the original index
// newIndex is a variable holding the new index
// initialise updatedItems so we can update within the loop
let updatedItems = update(this.state.items, { [originalIndex]: {'index': {$set: newIndex}}});
for (var i = newIndex; i < this.state.items.length; i++) {
if (i !== originalIndex) {
updatedItems = update(updatedItems, { [i]: {'index': {set$: parseInt(this.state.items[i].index) + 1}}});
}
}
這感覺就像一個巨大的黑客攻擊。
我的問題是,是否有可能用條件邏輯調用更新,所以這個循環可以用一次調用來更新嗎?
似乎有點哈克的'index'是每個對象內部的屬性,如果一切真的是指to是items數組中的索引。 –
同樣@TomFenech說。當元素可以被數組中的索引引用時,不需要索引屬性_within_ an – Pineda
這實際上是一個好點!我沒有想到這一點。 –