首页 > 解决方案 > 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',
      },
]

标签: reactjs

解决方案


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});
};

推荐阅读