【发布时间】: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