反应本机设置/访问函数内的变量 [英] React native setting/accessing a variable inside a function

查看:44
本文介绍了反应本机设置/访问函数内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量 lat 和 lng 设置为地理编码器返回的坐标.我认为可以从地理编码器代码内部访问 lat 和 lng,它说 Geocoder.getFromLocation(inputWhere).then(...),但除此之外,它似乎没有将变量设置为地理编码器的坐标.我是否缺少有关变量范围的信息?我已经评论了警报返回的内容.我已经测试过地理编码器工作正常并且if"条件得到满足.感谢任何帮助,谢谢!

I'm trying to set the variables lat and lng to the coordinates returned by the geocoder. I think that lat and lng are accessible from inside the geocoder code where it says Geocoder.getFromLocation(inputWhere).then(...), but then outside of that, it doesn't seem to have set the variables to the geocoder's coordinates. Am I missing something about the variable scope? I've commented what the alerts are returning. I've tested that the geocoder works fine and that the "if" condition is being satisfied. Any help appreciated, thanks!

submitData = (inputWhere) => {

var lat = 0;
var lng = 0;

if(inputWhere != '') {
  Geocoder.getFromLocation(inputWhere).then(
   json => { 
    var location = json.results[0].geometry.location;
    alert(lat); // Here it says 0
    lat = location.lat; // 40
    lng = location.lng;
    alert(lat); // Here it says 40
   },
   error => {
    alert(error);
   }
 );
 alert(lat); // Here it says 0
}
alert(lat); // Here it says 0

}

推荐答案

Geocoder.getFromLocation() 需要时间.

Geocoder.getFromLocation() takes time to occur.

你需要等到它完成

这篇关于反应本机设置/访问函数内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆