循环仅将最后一个元素添加到数组中

问题描述 投票:0回答:1

为什么只显示最后一项而不是全部? history2表仅显示最后一个元素,并且条件包含更多元素

state = {
history2:[]
}

 for (const point of this.state.idRt) {
      if (id === point.RouteId) {
        this.setState({
          history2: {
            Name: point.Name,
          }
        })
      }
    }
javascript reactjs
1个回答
0
投票

您应该附加到您拥有的状态对象上,而不是替换它。像这样的东西,

state = {
  history2: [],
};

for (const point of this.state.idRt) {
  if (id === point.RouteId) {
    this.setState({
      history2: [
        ...this.state.history2,
        {
          Name: point.Name,
        },
      ],
    });
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.