【问题标题】:React - setState within a for loop to add data to arrayReact - 在 for 循环中设置状态以将数据添加到数组
【发布时间】:2019-12-28 21:09:38
【问题描述】:

我有一组带有 lat/lng 坐标的位置。我正在使用距离计算函数来确定每个位置与谷歌地图中心的距离,以便按距离对数组进行排序,并在我的应用程序中呈现距离。目前我正在这样做:

for(var i=0; i < this.state.locations.length; i++) {
    this.state.locations[i]['distance'] = this.calculateDistance(this.state.locations[i].coords, this.state);
}

const sortedlocations = this.state.locations.sort((a, b) => a.distance - b.distance);
this.setState({locations: sortedlocations});

这实际上按预期工作,但我收到警告Do not mutate state directly. Use setState(),所以我想让它以正确的方式工作。我不太确定如何在这个 for 循环中使用 setState。我在下面尝试了只是在黑暗中刺了一下,但是没有用哈哈:

for(var i=0; i < this.state.locations.length; i++) {
    this.setState({
        locations[i]['distance']: = this.calculateDistance(this.state.locations[i].coords, this.state);
    })
}

这是this.state.locations 的示例:

[
  {
    "location": "Lorem Ipsum",
    "description": "Lorem Ipsum"
    "coords": {
      "lat": -50.12424,
      "lng": 80.04562
    }
  },
  {
    "location": "Lorem Ipsum 2",
    "description": "Lorem Ipsum 2"
    "coords": {
      "lat": -37.10005,
      "lng": 65.55088
    }
  },
  {
    "location": "Lorem Ipsum 3",
    "description": "Lorem Ipsum 3"
    "coords": {
      "lat": -56.39949,
      "lng": -98.10049
    }
  },
  {
    "location": "Lorem Ipsum 4",
    "description": "Lorem Ipsum 4"
    "coords": {
      "lat": -67.61780,
      "lng": 145.47068
    }
  }
]

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    你不应该直接改变状态。始终创建一个副本,对副本进行变异,然后使用新副本调用setState,以便它将在内存中创建一个新的对象引用。

    而不是这个:

    for(var i=0; i < this.state.locations.length; i++) {
        this.state.locations[i]['distance'] = this.calculateDistance(this.state.locations[i].coords, this.state);
    }
    

    试试这个:

    const locations = [ ...this.state.locations ];
    
    for(var i=0; i < locations.length; i++) {
        locations[i]['distance'] = this.calculateDistance(locations[i].coords, this.state);
    }
    

    然后像这样做剩下的:

    const sortedlocations = locations.sort((a, b) => a.distance - b.distance);
    this.setState({locations: sortedlocations});
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多