[英]Error with geocodeAync preventing function to shoot
在此处输入图像描述] 1 rybody 我正在构建一个基于位置的组件需要获取城市名称以通过 API 的获取请求来传递它,就像这样 axios.get( /${cityName}/JSON
);
在我写的组件中,有时运行良好,但大部分时间都给出了该错误( null 不是 object (评估'location.coords')])
如何克服它以及如何使用纬度和经度或任何其他方法单独获取 cityName
import React, { useState, useEffect } from 'react';
import { Platform, Text, View, Button } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
export default function App() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState('');
const getLocation = async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
console.log(location);
}
const getCity = async () => {
const place = await Location.reverseGeocodeAsync({
latitude : location.coords.latitude,
longitude : location.coords.longitude
});
setCity(place.city);
console.log(city);
}
useEffect(() => {
getLocation() , getCity();
} , []);
let text = 'Waiting..';
if (errorMsg) {
text = errorMsg;
} else if (location) {
text = JSON.stringify(location);
}
return (
<View >
<Text> </Text>
<Button title = 'press'
onPress = {getCity}
/>
</View>
);
}
所以,问题是当组件第一次在此处重新渲染时调用 getCity 而没有位置 object:
useEffect(() => {
getLocation() , getCity();
} , []);
这两个函数都是异步的,但这并不能保证它们会按那个顺序发生。 此外,会发生什么是函数并行运行,这会导致你的错误。
您在这里有多个选项: - 您可以将多个 Promise 链接在一起以确保执行顺序 - 您可以从上述 useEffect 中删除 getCity 调用,并仅在 getLocation 调用完成后调用它(不允许用户在此之前进行交互)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.