You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中GoogleMap组件未随经纬度状态更新的问题

问题原因与解决方案
  • 核心问题:useMemo依赖缺失
    你的Map组件里,useMemo创建center时依赖数组是空的[]。这意味着center只会在组件第一次渲染时计算一次,之后哪怕latitude和longitude props更新,center也不会重新生成。而GoogleMap的center属性、Marker的position属性都绑定了这个不会更新的center,所以地图自然不会跟着状态变化刷新。

  • 修复步骤
    修改Map组件的useMemo,把latitude和longitude加入依赖数组:

    function Map({latitude,longitude}:{latitude:number,longitude:number}) {
      const center = useMemo(() => ({
        lat: latitude,
        lng: longitude
      }), [latitude, longitude]); // 添加依赖项
    
      return (
        <GoogleMap zoom={17} center={center}
                   mapContainerClassName="map-container">
          <Marker position={center} />
        </GoogleMap>
      );
    }
    
  • 额外优化建议
    你的GeoMap组件同时维护了theGPS、theLatitude、theLongitude三个状态,存在冗余。可以合并成单个状态,简化代码并避免多状态同步问题:

    export default function GeoMap({shop,gps}:{shop: string, gps: string;}) {
      const [coords, setCoords] = useState({latitude:0.0, longitude:0.0})
      const dbRef = ref(firebaseDatabase, 'MyApp/'+shop)
    
      useEffect(() => {
        onValue(dbRef, (snapshot) => {
          const coordsStr = snapshot.child('gPS').val().split(',')
          const latit = parseFloat(coordsStr[0])
          const longit = parseFloat(coordsStr[1])
          console.log('shop='+shop)
          console.log('coordsStr='+coordsStr)
          console.log('latit='+latit.toString())
          console.log('longit='+longit.toString())
          setCoords({latitude: latit, longitude: longit})
        }, (error) => {
          console.log('Error(onValue): '+error);
        });
      }, [])
    
      return <Map latitude={coords.latitude} longitude={coords.longitude} />
    }
    

内容的提问来源于stack exchange,提问作者Michel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:06:15