当单击地图区域时尝试使用纬度和经度从 API 获取时遇到问题。初始地图加载很好,来自 API 的数据按预期显示,我可以确认 geoLoc 数组状态正在更新 onClick,因为控制台日志显示了这一点。但是,由于某种原因,即使 geoLoc.latitude 和 geoLoc.longitude 的状态都在变化,API 也不会更新。这有什么原因吗?任何帮助将非常感激!谢谢
const Maps = () => {
const [events, setEvents] = useState([])
const handleClick = (e) => {
console.log(geoLoc)
e.preventDefault()
setGeoloc({ ...viewport })
}
useEffect(() => {
fetch(`https://api.list.co.uk/v1/events?near=${geoLoc.latitude},${geoLoc.longitude}/5`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
})
.then(res => res.json())
.then(res => setEvents(res))
console.log(geoLoc.latitude)
return () => console.log('Unmounting component')
}, [])
const [viewport, setViewport] = useState({
width: '100vw',
height: '100vh',
latitude: 51.45523,
longitude: -2.59665,
zoom: 13.5
})
const [geoLoc, setGeoloc] = useState({
latitude: 51.45523,
longitude: -2.59665
})
if (events.length === 0) {
return <div>Loading...</div>
}
return <div>
<ReactMapGL mapboxApiAccessToken={TOKEN}
mapStyle="mapbox://styles/dredizzle/ck3owxclr138a1cqnzupab2hc"
{...viewport}
onViewportChange={viewport => {
setViewport(viewport)
}}
onClick={handleClick}
>
{events.map(event => (
<Popup
key={event.event_id}
latitude={event.schedules[0].place.lat}
longitude={event.schedules[0].place.lng}
>
</Popup>
))}
{/* <Popup latitude={51.45523} longitude={-2.59665}>
<div>event here</div>
</Popup> */}
<GeolocateControl
positionOptions={{ enableHighAccuracy: true }}
trackUserLocation={false}
/>
</ReactMapGL>
</div>
}
export default Maps