问题描述
我尝试制作的一个应用程序涉及从我的服务器中获取附近标记的部分。
我确定我的位置挂钩函数可以正常工作,但是在我进行API调用以获取该位置附近的标记之前,它还没有完成。
这使我困惑了几个小时,所以任何帮助将不胜感激!
import React,{ useEffect,useState } from "react";
import MapView,{ PROVIDER_GOOGLE,Marker } from "react-native-maps";
import { StyleSheet,View,Dimensions,Platform } from "react-native";
import useLocation from "../hooks/useLocation";
import useApi from "../hooks/useApi";
import couponsInArea from "../api/couponsInArea";
const customData = require("../assets/map_styles/day_map.json");
function MapScreen(props) {
//Here is the location hook
var location = useLocation();
const couponBaseApi = useApi(couponsInArea.getCouponBases);
//Here is the API call that needs the location
useEffect(() => {
if (location) {
couponBaseApi.request(location.latitude,location.longitude);
}
},[]);
return (
<View style={styles.container}>
<MapView
followUserLocation={true}
zoomEnabled={true}
showsUserLocation={true}
style={styles.mapStyle}
provider={PROVIDER_GOOGLE}
customMapStyle={customData}
initialRegion={{
latitude: location.latitude,longitude: location.longitude,latitudeDelta: 0.0158,longitudeDelta: 0.007,}}
>
{couponBaseApi.data.couponBases.map((report) => (
<Marker
key={report.couponBaseID}
coordinate={{
latitude: report.latitude,longitude: report.longitude,}}
></Marker>
))}
</MapView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},mapStyle: {
width: Dimensions.get("window").width,height: Dimensions.get("window").height,});
export default MapScreen;
解决方法
解决方案是使用效果挂钩需要监视位置的变化, 所以
useEffect(() => {
if (location) {
couponBaseApi.request(location.latitude,location.longitude);
}
},[location]);
谢谢大家!