我正在使用react-native-simple-store并编写了以下函数来更新存储在对象数组中的所提供对象的属性。为此,我使用了issue #31中提到的方法。用于删除项目。
问题是因为我使用的是 .push,所以更新项目会导致它呈现在数组的底部。这会导致项目在 FlatList 中不必要地移动。
是否有更有效的方法来更新数组中对象的属性(使用 .push 不会导致此问题)?
plusProgress = (itemId, progress) => {
const foods = this.state.foods.filter(({ id }) => itemId !== id);
const updatedItem = {
itemId,
progress: progress + 1
};
foods.push(updatedItem);
this.setState({ foods });
store.save('foods', foods);
}
最佳答案
创建一个新数组,并将更新后的对象放置在正确的位置,然后使用该新数组调用 setState()。如果当前项目不是您要更新的项目,请务必按原样返回。否则,数组元素将被 null 替换
plusProgress = (itemId, progress) => {
const foods = this.state.foods.map(item => {
if (item.itemId === itemId) {
return Object.assign({}, item, {progress: progress + 1});
}
return item
})
this.setState({ foods: foods })
}
关于arrays - 更新存储数组中对象的属性 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817714/