javascript - ReactJS: replacing object from array with new value replaces whole array
问题描述
I have array selectedItems
and when I try to update existing object:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 1}]
to:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 3}]
It replaces the whole array with:
[ { lable: "two", uniqueId: 3 }]
how can I avoid that?
handleChange = (label, uniqueId) => {
const { selectedItems } = this.state
const findExistingItem = selectedItems.find((item) => {
return item.uniqueId === uniqueId;
})
if(findExistingItem) {
selectedItems.splice(findExistingItem);
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
} else {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
}
}
解决方案
另一种方法是串联使用Array#filter
和Array#concat
函数,其中;
- 不匹配的项目将
uniqueId
被过滤。这取代了find()
您当前解决方案的逻辑,然后, - 被调用的
concat()
方法以将新的“替换项”附加到过滤数组的末尾
在可以这样实现的代码中:
handleChange = (label, uniqueId) => {
const {
selectedItems
} = this.state
this.setState({
selectedItems : selectedItems
/* Filter any existing item matching on uniqueId */
.filter(item => (item.uniqueId !== uniqueId))
/* Append replacement { label, uniqueId } to state array */
.concat([ { label, uniqueId } ])
});
}
推荐阅读
- spring - 如何将自定义过滤器应用于特定网址?
- wso2 - API 网关未与反向代理 WSO2 连接
- spyder - Linting 不再显示在 Spyder 的侧边栏上?
- json - 出现错误:无法在 React 中使用 Fetch 读取未定义的属性“地图”?
- logistic-regression - 如何在 Weka 中修改逻辑回归模型的系数?
- laravel - 从博客文章标题制作网址。Laravel
- javascript - 内部 Html 表格样式
- r - R geom_histogram position="identity" 不一致
- swift - 带有空字段的 Swift ui 可编码结构
- c# - 尝试连接 MQTT 代理并尝试从代理接收消息并将其显示到控制台