Javascript 从React中的嵌套函数内部返回值时出现问题。可能是作用域,但可能是异步问题
我正在将自定义位置api连接到谷歌地图。在每个locations longLat属性上,我调用一个函数Javascript 从React中的嵌套函数内部返回值时出现问题。可能是作用域,但可能是异步问题,javascript,reactjs,scope,google-distancematrix-api,Javascript,Reactjs,Scope,Google Distancematrix Api,我正在将自定义位置api连接到谷歌地图。在每个locations longLat属性上,我调用一个函数CalculateInstances,以获取Google距离矩阵API调用所需的参数 以下是该呼叫发生的地方: {Object.keys(this.state.locations).map((i) => { let locale = this.state.locations[i]; return <Location name={locale.name} addres
CalculateInstances
,以获取Google距离矩阵API调用所需的参数
以下是该呼叫发生的地方:
{Object.keys(this.state.locations).map((i) => {
let locale = this.state.locations[i];
return <Location name={locale.name}
address={locale.address}
longLat={locale.longLat}
needsCode={locale.needsCode}
needsKey={locale.needsKey}
distances={this.calculateDistances(locale.longLat)}
handicapAccess={locale.handicapAccess}
code={locale.code}
id={locale.id} />
})},
这非常有效,并且在嵌套函数dist中定义正确。但是,我无法从整个calculatedInstances
函数返回dist
变量
所以distance.matrix
正在进行api调用(google distance matrix作为distance
导入到组件顶部),并正确设置dist
变量
如何获取由“总体
calculatedInstances
函数返回的dist?到目前为止,它正在返回未定义的
,我想简单的答案是你不能。由于distance.matrix
是异步的,因此calculatedInstances
函数将在distance.matrix
调用完成之前返回。您试图如何使用计算实例
?也许解决办法在于你打算如何使用这个函数。
calculateDistances(longLat) {
const origins = [Object.values(this.state.currentLocation).join()];
const destinations = [Object.values(longLat).join()];
const travelMode = this.state.travelMode.length ? this.state.travelMode : 'WALKING';
distance.matrix(origins, destinations, travelMode, (err, distances) => {
let dist = distances.rows[0].elements[0].distance.text;
})
return dist;
}