reactjs - geocodeAync 错误阻止功能拍摄
问题描述
在此处输入图像描述] 1 rybody 我正在构建一个基于位置的组件,需要获取城市名称以通过获取 API 请求来传递它,就像这样 axios.get( /${cityName}/JSON
);
在我编写的组件中,有时运行良好,但大部分时间都给出了错误(null 不是对象(评估'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 ,而没有位置对象:
useEffect(() => {
getLocation() , getCity();
} , []);
这两个函数都是异步的,但这并不能保证它们会按那个顺序发生。此外,会发生什么是函数并行运行,这会导致你的错误。
您在这里有多个选项:-您可以将多个承诺链接在一起以确保执行顺序-您可以从上述 useEffect 中删除 getCity 调用,并仅在 getLocation 调用完成后调用它(不允许用户在此之前进行交互)
推荐阅读
- linux - 如何快速找到链接时需要存在另一个对象图块的对象文件?
- vim - Vim 无法识别来自 vim-latex 的某些命令
- python - 从 Python 2 转换为 3。使用 cmp 进行排序
- c# - 关于在 C# 中执行 while 循环的问题
- c++ - 如何从棋盘上的框号中查找行和列?
- c# - 必须通过 Modbus TCP 通过 Modbus RTU 为轮询 RS485 编写客户端吗?
- asynchronous - 使用带有颤振地图的期货
- c - 如何检查本身是无符号变量的负数(通过用户输入)?
- php - 如何在 PHPUnit 测试中“模拟”Sentry 客户端
- android - 使用导航组件在父片段范围内共享 ViewModel