首页 > 解决方案 > 不使用状态获取设备经纬度

问题描述

在我的操作文件夹(使用 redux)中,我想获取设备位置,以便可以使用它来查询 firestore,我的代码返回undefined。我不确定我的错误来自哪里。知道如何获取设备位置而不将其存储在我的状态中吗?

const myCoord = navigator.geolocation.getCurrentPosition(position => {
        const { latitude, longitude } = position.coords;
        const LatLong = {
            'lat': latitude,
            'long': longitude
        }
        return LatLong
    });

标签: reactjsreact-native

解决方案


你得到 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() 函数


推荐阅读