reactjs - 不使用状态获取设备经纬度
问题描述
在我的操作文件夹(使用 redux)中,我想获取设备位置,以便可以使用它来查询 firestore,我的代码返回undefined。我不确定我的错误来自哪里。知道如何获取设备位置而不将其存储在我的状态中吗?
const myCoord = navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
const LatLong = {
'lat': latitude,
'long': longitude
}
return LatLong
});
解决方案
你得到 undefined 因为 getCurrentPosition 没有立即完成。这是一个异步函数。例如,您可以做的是创建一个 Promise,它将在 getCurrentPosition 成功时完成并在错误时被拒绝。
这是我如何实现的:
const myCoord = () =>
new Promise((resolve, reject) => {
const geoSuccess = position => resolve(position);
const geoFailure = error => reject(error);
navigator.geolocation.getCurrentPosition(
geoSuccess,
geoFailure,
geoOptions
);
const geoOptions = {
timeout: 5000,
maximumAge: 5000,
enableHighAccuracy: false
};
});
然后你需要用“then”或“async”调用
我建议在此处阅读有关将回调更改为 Promises的信息
从这个网站引用最能描述您的问题
在理想情况下,所有异步函数都会返回 Promise。不幸的是,一些 API 仍然希望以旧方式传递成功和/或失败回调。最明显的例子是 setTimeout() 函数
推荐阅读
- email - 如何使用 email-ext 插件在 Jenkins 中设置地址?
- c# - FileHelpers async 使用 MultiRecordEngine?
- postgresql - PL/PQSQL 存储过程:这两种方法有什么区别?
- resolve - DCOS 在 resolv.conf 中添加 DNS 条目
- json - 无法在本机反应中获取数据数组
- jenkins - 在 Jenkins 上具有并行作业执行的单一报告
- python - Google Adwords API TargettingIdeaService 设备类型
- java - Java - 如何将提取的 pdf 文件中的单词集成到 MYSQL 以进行索引?
- wordpress - wordpress 将子页面作为参数传递
- java - for循环内的条件问题(JAVA)