reactjs - reactjs更新状态数组中的所有项目
问题描述
有没有更好的方法来更新数组中的所有项目?
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',
},
]
解决方案
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});
};
推荐阅读
- twig - 带有 Drupal 8 的树枝:{% if content.field_ %} 两个相似字段之间的结果不一致
- javascript - AJAX 搜索与 Laravel 和 Vue 空结果
- r - 尝试在 R - NA 时间戳记录中创建移动对象
- docker - 如何在 VS2017 中清除 docker-compose 镜像名称
- algorithm - 根据位出现查找集合
- javascript - 如何在反应js中解码包含base 64 png的二维码
- omnet++ - 如何在静脉中记录 rssi (omnet++)
- python - 如何避免复数并获得浮点数?
- javascript - 检查选中的单选按钮是否返回 true 但应该为 false
- scala - Scala:克服隐式解析的泛型类型擦除