簡體   English   中英

當 console.log 時,useEffect 和 getCoordinates 內部的相同數組不同

[英]Same array inside of useEffect and getCoordinates is different when console.log

使用 GoogleMap API 顯示自定義位置

我有一個稱為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM