React Native Geolocation 变量无法访问

React Native Geolocation variables unacessable

这就是我的问题,我现在正在开发一个 React 本机应用程序,除了函数 getLocation() 之外,所有代码都可以正常工作。它的工作原理是它 returns 一个纬度和经度,但由于某种原因它花费的时间太长,当我 运行 一个依赖于值的函数时,它不会 运行调用该函数的时间。有什么办法可以延迟函数,使其在 getLocation() 函数 returns 时具有经纬度吗?

我之前做了一些研究,这是另一个有点类似的堆栈溢出问题,但是他们使用了不同的方式来获取位置。

如有任何帮助,我们将不胜感激!

import React, { Component } from 'react';
import { ActivityIndicator, ListView, Text, View, Picker } from 'react-native';

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            dataSource: null,
            key: "KEY NOT SHOWN BUT WORKS",
            latitude: null,
            longitude: null,
            error: 2
        };
    }


    /**
     * This function gets the current geo location of the device and stores it
     * as Lat and Long coordinates.
     * @private
     */
    getLocation(){
        navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                });
            },
            (error) =>
                this.setState({ error: error.message, latitude: 41.77, longitude: -88.07,}),
            { enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
        );
    }

    getAPI(){
        fetch('https://developer.cumtd.com/api/v2.2/JSON/getstopsbylatlon?key='+this.state.key+'&lat='+this.state.latitude.toString()+'&lon='+this.state.longitude.toString())
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    dataSource: responseJson.stops,
                    isLoading: false,
                }, function() {
                    // do something with new state
                });
            })
            .catch((error) => {
                //error
            });
    }

    componentDidMount() {
        this.getLocation();
        this.getAPI();
    }



    render() {
        if (this.state.isLoading) {
            return (
                <View style={{flex: 1, paddingTop: 20}}>
                    <ActivityIndicator />
                </View>
            );
        }
        return (
            <View style={{flex: 1, paddingTop: 20}}>
                <Text>Latitude: {this.state.latitude}</Text>
                <Text>Longitude: {this.state.longitude}</Text>
                <Picker
                    selectedValue={this.state.dataSource}>
                    {this.state.dataSource.map((item, key)=>(
                        <Picker.Item label={item.stop_name} value={item.stop_name} key={key}/>))}
                </Picker>
            </View>
        );
    }
}

Here is a snack with a proposed solution

检索位置后,只需将 API 调用移至 getLocation()。 当您集成权限处理时,您将希望转向更加基于 Promise 的结构。