【发布时间】:2021-01-03 18:19:32
【问题描述】:
我刚刚开始使用 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,
}
});
【问题讨论】:
标签: reactjs react-native geolocation expo