gpt4 book ai didi

javascript - ReactJS:无法从函数中获取数据

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

我目前在访问函数内的值时遇到问题,但这超出了 promise 。

这是我的代码:

 service.getDistanceMatrix({
origins: ["Waterloo ON"],
destinations: destination,
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;

for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
// _this.
// console.log(distance);
location.distFinal = distance;

location.setState({
dist: distance
})
// return distance;
// return distance;
// console.dir(distance)
// tryA = distance;
}
}

}
})
console.dir(location);
console.dir(location.distFinal);

我试图访问距离,所以我做了 console.dir(location.distFinal) 但它给了我一个未定义的值。但是,当我执行 console.dir(location) 时,它给了我以 distFinal 作为值的对象......

这就是我的意思:

enter image description here

第126行是console.dir(location),第127行是console.dir(location.distFinal)

拜托!我只是想能够提取距离!

最佳答案

目前它不在 Promise 中,因此请尝试将其转换为 Promise - 这样,一旦异步代码具有所需的数据,您就可以解析。然后,您可以 .then promise 在解析后运行代码。

//  location is defined somewhere up here
new Promise((resolve, reject) => {
service.getDistanceMatrix({
origins: ["Waterloo ON"],
destinations: destination,
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;

for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
// _this.
// console.log(distance);
location.distFinal = distance;

location.setState({
dist: distance
})
// return distance;
// return distance;
// console.dir(distance)
// tryA = distance;
}
}
// looping is done
resolve();
}
})
}).then(() => {
console.dir(location);
console.dir(location.distFinal);
});

您可以console.dir的原因是因为Chrome的控制台在您打开控制台时请求对象的状态,而不是显示对象的状态>原样

关于javascript - ReactJS:无法从函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441794/

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