是否有更好的方法来更新数组中的所有项目?
deselectAllTags = () => {
const tags = this.state.tags;
this.state.tags.map((tag, i) => {
tags[i].isSelected = false;
return null;
});
this.setState({tags});
};
状态数组如下:
tags: [
{
isActive: true,
isSelected: true,
name: 'cake',
},
{
isActive: true,
isSelected: true,
name: 'chocolate',
},
]
答案 0 :(得分:1)
map
返回另一个数组,因此您可以简单地做到这一点:
deselectAllTags = () => {
const tags = this.state.tags.map((tag, i) => {
return { ...tag, isSelected: false };
});
this.setState({tags});
};
或者如果您没有散布物体:
deselectAllTags = () => {
const tags = this.state.tags.map((tag, i) => {
tag.isSelected = false;
return tag;
});
this.setState({tags});
};