Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从React中的嵌套函数内部返回值时出现问题。可能是作用域,但可能是异步问题_Javascript_Reactjs_Scope_Google Distancematrix Api - Fatal编程技术网

Javascript 从React中的嵌套函数内部返回值时出现问题。可能是作用域,但可能是异步问题

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

我正在将自定义位置api连接到谷歌地图。在每个locations longLat属性上,我调用一个函数
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;
}