gpt4 book ai didi

javascript - React 变量不更新

转载 作者:行者123 更新时间:2023-12-02 23:52:52 25 4
gpt4 key购买 nike

我一直在尝试使用 Google Maps API 计算多个地点之间的总行程时间。但是,当尝试使用上述信息访问变量 total_duration 时,控制台上没有显示任何内容。

const responses = [];
let total_duration = 0;
for(let i = 0 ; i < origins.length ; i++){
const matrix = new google.maps.DistanceMatrixService();
matrix.getDistanceMatrix({
origins: origins[i],
destinations: destinations[i],
travelMode: google.maps.TravelMode.DRIVING,
},
function(response, status){
responses.push(response);
});
}
console.log(responses);
for(let i = 0 ; i < responses.length ; i++){
total_duration += responses[i].rows[0].elements[0].duration.value;
console.log(responses[i])
}
console.log(total_duration);

第一个控制台日志向我显示了每几个位置的所有结果。

[
{
"rows": [
{
"elements": [
{
"distance": {
"text": "1.2 km",
"value": 1161
},
"duration": {
"text": "3 mins",
"value": 169
},
"status": "OK"
}
]
}
],
"originAddresses": [
"3670 SW 3rd St, Miami, FL 33135, USA"
],
"destinationAddresses": [
"3911 SW 2nd Terrace, Coral Gables, FL 33134, USA"
]
},
{
"rows": [
{
"elements": [
{
"distance": {
"text": "1.5 km",
"value": 1473
},
"duration": {
"text": "4 mins",
"value": 226
},
"status": "OK"
}
]
}
],
"originAddresses": [
"3911 SW 2nd Terrace, Coral Gables, FL 33134, USA"
],
"destinationAddresses": [
"4490 SW 5th Terrace, Coral Gables, FL 33134, USA"
]
}
]

但是其他控制台日志没有显示我需要的信息。你能帮我解决这个错误吗?预先感谢您。

现在,当我尝试在 getTimes 函数中更新 state 时,我的状态不会更新。时间始终为0


import React, {Component} from 'react';

class HomePage extends Component {

constructor(props) {
super(props);

this.state = {
time: 0,
places: [
{latitude: some_data, longitude: some_data},
{latitude: some_data, longitude: some_data}
]
};
}

componentDidMount(){}

getTimes = () => {
const origins = [], destinations = [];
for(let i = 0 ; i < this.state.places.length - 1 ; i++){
origins.push([new google.maps.LatLng(this.state.places[i].latitude,
this.state.places[i].longitude)]);
destinations.push([new google.maps.LatLng(this.state.places[i + 1].latitude,
this.state.places[i + 1].longitude)]);
}
let total_duration = 0;
for(let i = 0 ; i < origins.length ; i++){
const matrix = new google.maps.DistanceMatrixService();
matrix.getDistanceMatrix({
origins: origins[i],
destinations: destinations[i],
travelMode: google.maps.TravelMode.DRIVING,
},
(response, status) => {
total_duration += response.rows[0].elements[0].duration.value;
console.log(total_duration);
this.setState({time: total_duration});
});
}
console.log(this.state.time);
}

render() {
const {time} = this.state;
return (
<h1>{time}</h1>
);
}
}

最佳答案

 this.setState(state => {
const newTime = state.time + total_duration
return { count: newTime }
}, () => {
console.log(this.state.time);
})

关于javascript - React 变量不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com