reactjs - 基于用户位置的 React Native API 调用
问题描述
我刚刚开始使用 react 和 react native 我的目标是获取用户位置,并根据位置坐标进行 API 调用并显示结果。我哪里出错了?我正在使用带有 aqicn API 库的 EXPO 项目。
这是代码。
import React,{ useState , useEffect} from 'react';
import { StyleSheet, Text, View ,Button} from 'react-native';
import * as Location from 'expo-location';
import Constants from 'expo-constants';
import axios from 'axios';
//First get location - Done
//get latitude & longitude - Done
//Call the api with latitude and longitude
//Display results
export default function HomeScreen({navigation}) {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
//Lat and Long
const [latitude, setLatitude] = useState(null);
const [longitude , setLongitude]= useState(null);
const [data, setData] = useState([]);
useEffect(() => {
(
async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission Denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
//Changes
setLatitude(location.coords.latitude);
setLongitude(location.coords.longitude);
})();
}, []);
const la=latitude;
const lo=longitude;
console.log(la , lo);
let res = fetch("https://api.waqi.info/feed/geo:"+ la +";"+ lo +"/?token=ac3a71fc80931abd95ede14c2040f0678f578703")
.then((response) => response.json())
.then((json) => setData(json.data))
.catch((error) =>console.log(error))
console.log(data);
return (
<View style={styles.container}>
<Text style={styles.paragraph}></Text>
</View>
);
}
const styles= StyleSheet.create({
container: {
padding:20,
marginTop:15,
margin:10,
},
paragraph : {
padding:20,
marginTop:5,
}
});
解决方案
我想我知道你的问题是什么。仅当您填写了纬度和经度状态时,您才必须执行请求。您可以使用钩子 useEffect 确保这一点。您的代码必须是这样的:
useEffect(() => {
/** Creating an useEffect like this
you ensure that the latitude and longitude state are filled. Therefore,
your request is going to work :).
**/
async function anyNameFunction() {
let res = fetch("https://api.waqi.info/feed/geo:"+ latitude +";"+ longitude +"/?token=ac3a71fc80931abd95ede14c2040f0678f578703")
.then((response) => response.json())
.then((json) => setData(json.data))
.catch((error) =>console.log(error))
console.log(data);
}
anyNameFunction();
}, [latitude, longitude]);
如果您有任何疑问,请随意询问更多:)。等待您的反馈,如果答案是正确的,请竖起大拇指!
推荐阅读
- typescript - NuxtJS 代理以避免 CORS
- python - Pygame中如何让物体向前跳跃?
- azure-data-factory-2 - Azure Datafactory 运行并行活动
- discord.py - 在 discord.py 中添加角色失败,没有错误
- r - 函数内 set_tag() 时未找到 AzureRMR 对象
- excel - 用 VBA 替换引号
- c - 当用户空间应用程序连接到它时,无法删除 netlink 内核模块
- java - 使用哈希集比较数据
- android - Unity:在 Unity 中制作界面的最佳方式
- docker - Docker NFS 卷权限被拒绝