首页 > 解决方案 > 在 React Native 中获取经纬度的设置状态

问题描述

我正在创建一个需要获取用户纬度和经度的应用程序。

我正在使用 react-native-geolocation-services 来获取信息。

这是我的代码。

 componentDidMount() {
    hasLocationPermission().then(result => {
      this.setState({_isLocationEnabled: result});
    });
    if (hasLocationPermission) {
      Geolocation.getCurrentPosition(
        position => {
          this.setState({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          });
          console.log(this.state.latitude);
          console.log(this.state.longitude);
        },
        error => {
          console.log(error.code, error.message);
        },
        {
          enableHighAccuracy: true,
          timeout: 15000,
          maximumAge: 10000,
        },
      );
    }
    const fetch = require('node-fetch');
    console.log(this.state.latitude);
    fetch(
      'https://api.weatherapi.com/v1/forecast.json?q=' +
        this.state.latitude +
        ',' +
        this.state.longitude,
      {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      },
    )
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      .catch(error => {
        console.error(error);
      });
  }

从我的代码中可以看出,如果设备具有位置权限,那么我将获得地理位置和当前位置。在此之后,我设置了纬度和经度的状态。当我打印它们时,它们会被发送到控制台。

当我尝试通过添加 this.state.latitude 在我的 fetch url 中使用它们时,它们是未定义的。为什么是这样?我究竟做错了什么?

标签: javascriptreact-nativegeolocation

解决方案


问题是Geolocation.getCurrentPosition异步的,所以当您收到位置时,执行获取的代码已经执行。

为了解决这个问题,您需要执行以下操作:

componentDidMount() {
hasLocationPermission().then(result => {
  this.setState({_isLocationEnabled: result});
});
if (hasLocationPermission) {
  Geolocation.getCurrentPosition(
    position => {
      this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      }, () => {
        const fetch = require('node-fetch');
        console.log(this.state.latitude);
        fetch(
          'https://api.weatherapi.com/v1/forecast.json?q=' +
            this.state.latitude +
            ',' +
            this.state.longitude,
          {
            method: 'GET',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
          },
        )
          .then(response => response.json())
          .then(responseJson => {
            console.log(responseJson);
            this.setState({
              isLoading: false,
              dataSource: responseJson,
            });
          })
          .catch(error => {
            console.error(error);
          });
      });
      console.log(this.state.latitude);
      console.log(this.state.longitude);
    },
    error => {
      console.log(error.code, error.message);
    },
    {
      enableHighAccuracy: true,
      timeout: 15000,
      maximumAge: 10000,
    },
  );
}

基本上,您需要在setState完成后执行获取,以便您可以读取更新的状态。


推荐阅读