【发布时间】:2021-12-31 08:52:11
【问题描述】:
我希望我的函数 calculateDistance 根据状态数组返回一个新数组。
所以一旦用户按下按钮,handle 方法就会被激活:
handleSearch(result){
this.setState({
teams: this.calculateDistance(result),
})
}
calculateDistance(result){
let map = L.map('route-map').setView([52.237049, 21.017532], 11);
const newTeams = []
this.state.teams.forEach((team) => {
const newTeam = {}
let routeControl = L.Routing.control({
waypoints: [
L.latLng(team.lat, team.long),
L.latLng(result.y, result.x)
],
show: true,
}).addTo(map)
routeControl.on('routesfound', function(e) {
let routes = e.routes;
let dist = routes[0].summary.totalDistance;
Object.defineProperty(newTeam, 'distance', {
value: dist,
writable: false
})
Object.defineProperty(newTeam, 'id', {
value: team.id,
writable: false
})
})
newTeams.push(newTeam)
})
return newTeams
this.state.teams 是从 axios GET 方法中检索到的数组。 首先,我尝试为每个团队添加一个新值。它适用于该对象,但不适用于 stringify - 这并没有导致任何变化。 然后我想我将创建一个新对象,这就是这个问题中提到的代码。 我尝试使用异步。 它确实返回了一个带有结果的承诺(我使用 console.log(promise) 签入,但状态没有更新(使用 .then() 后,没有任何值)。
【问题讨论】:
-
更新状态时,需要使用
this.setState
标签: javascript arrays reactjs json object