[英]Same array inside of useEffect and getCoordinates is different when console.log
我有一個稱為data
導入的 json object 數組; 它有一個名為地址的屬性。 Google map api 查找地址屬性的坐標,並應從名為位置的數組生成自定義標記。
但是當我使用 console.log 時, fetchLocations()
和getCoordinates
中的位置值是不同的,盡管它們都代表同一個變量。
我做錯了什么?
import React, { useEffect, useState } from 'react'
import { GoogleMap, useLoadScript, InfoWindowF, MarkerF } from "@react-google-maps/api"
import { data } from './data'
const API_KEY = "1234567890"
export default function MyComponent() {
const { isLoaded }: any = useLoadScript({
googleMapsApiKey: API_KEY,
})
const result : any[] = [];
const [locations, setLocations] = useState(result);
useEffect(() => {
const fetchLocations = async () => {
const locations = await Promise.all(data.map(getCoordinates));
console.log("Locations in fetchLocations", locations)
};
fetchLocations();
}, []);
const getCoordinates = async (obj: any) => {
const objData = await fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + obj.address + '&key=' + API_KEY)
const response = await objData.json()
const latitude = response.results[0].geometry.location.lat;
const longitude = response.results[0].geometry.location.lng;
const position = { 'lat': latitude, 'lng': longitude }
locations.push(position)
console.log("Locations in get Cooordinate", locations)
}
if (!isLoaded) return <div>Loading...</div>
return (
<div className='flex flex-col'>
<GoogleMap
zoom={11}
center={{ lat: 35.685661305110415, lng: 139.75255896834707 }}
mapContainerClassName='w-full h-[32em] m-2 rounded-lg'
>
<>
{locations.map(location=>{
return(
<>
<MarkerF
position={{ lat: location.lat, lng: location.lng }}
/>
</>
)
})
}
</>
</GoogleMap>
<button onClick={() => { setSelected(!selected) }}>Click</button>
</div>
)
}
locations
數組不應以任何方式更改。 它應該是不可變的。 唯一能夠改變它的是setLocations
function。
而不是locations.push(position)
做:
setLocations([...locations, position])
此外, getCoordinates
沒有返回任何內容。 它應該返回發送到setLocations
的相同值:
return [...locations, position]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.