簡體   English   中英

Firebase 值不不斷更新

[英]Firebase values not updating constantly

您好,我下面的代碼是使用拖放標記為用戶獲取緯度和經度。 當我 console.log 時,緯度和經度在控制台中不斷更新,但這不會發生在 firebase 上,我不明白為什么。

我下面的代碼是使用 leaflet 地圖處理此問題的代碼。

我正在使用如下所示的反應掛鈎將其寫入 firebase。 但我認為我的錯誤可能出在 useEffect 中,但我不確定如何解決。

                    location={location}
                    draggable={true}
                    title="sample text"
                    onDragMarker={(e) => {
                        console.log("e",e);
                        let loc = {lat: e.lng, lng:e.lat};
                        setLocation(loc);
                        setLongitude(e.lat)
                        setLatitude(e.lng)
                    }}

import React, {useState,useEffect } from "react";
import dynamic from "next/dynamic";
import 'firebase/firestore';
import 'firebase/firestore';
import fire from 'firebase/app'



const OsmMapNoSSR = dynamic(() => import("../../components/Map/osmMap.js"),{
    ssr: false,
});

export default function Home() {
    const coordinates = []
    
    const [latitude, setLatitude] = useState("")
    const [longitude, setLongitude] = useState("")

    navigator.geolocation.getCurrentPosition(function(position) {
        
        //setLatitude(position.coords.latitude );
        //setLongitude(position.coords.longitude);
     
 }); 
    const[location, setLocation] = useState({ lng: 53.363392004396104, lat: -6.209536});


    console.log(latitude,longitude, " loooooool")
    const getData = async () => {
        let currentUserUID = fire.auth().currentUser.uid
      
              const db = fire.firestore();
            
              const doc = await fire
              .firestore()
              .collection('LocationChoice')
              .doc(currentUserUID)
              .get()
              ///firefunctions.addfavs
                db.collection("LocationChoice")
                .doc(currentUserUID)
                .set({
                  lat: latitude,
                  long: longitude,
                  latlng: location
                })
                
            }
      
              useEffect(() => {
                let mounted = false
        
                if(!mounted){
                  
                   getData()
                }
                
                return () => {
                    mounted = true
                   // getData()
                }
            
            }, [])
        

//     lng: 53.363392004396104
// lat: -366.1387451118992



// const showMyLocation = () => {
//     if (location.loaded && !location.error) {
//       mapRef.current.leafletElement.flyTo(
//         [location.coordinates.lat, location.coordinates.lng],
//         ZOOM_LEVEL,
//         { animate: true }
//       );
//     } else {
//       alert("error");
//     }
//   };


// const map = useMapEvents({
//     click() {
//       map.locate()
//     },
//     locationfound(e) {
//       setPosition(e.latlng)
//       map.flyTo(e.latlng, map.getZoom())
//     },
//   })

    return(
        <div>
            <OsmMapNoSSR

                center={location}
                location={location}
                draggable={true}
                title="sample text"
                onDragMarker={(e) => {
                    console.log("e",e);
                    let loc = {lat: e.lng, lng:e.lat};
                    setLocation(loc);
                    setLongitude(e.lat)
                    setLatitude(e.lng)
                }}
                
                
            />    
            
            
            {"lng: "+ location.lng}
            <br />
            {"lat: " + location.lat}
           

            {/* <button onClick={showMyLocation}>
Locate Me  
</button> */}
        </div>



        
    );
}

目前,您只在掛載時調用一次getData方法。 useEffect中指定您的依賴項數組, 請參閱文檔,以包含應再次觸發掛鈎的值。

下面是一個在latitudelongitude上觸發的useEffect ,它有一個加載標志isLoading (否則你會用相同的值多次更新 Firestore)。 請注意,下面的代碼僅供說明之用,既未完成也未經過測試。

const [isLoading, setIsLoading] = useState(false)
const [latitude, setLatitude] = useState("")
const [longitude, setLongitude] = useState("")

const updateLocationInFirestore = useCallback(async (lat, lng) => {
  setIsLoading(true)

  await db.collection("LocationChoice").doc(currentUserUID).set({
    lat: lat,
    long: lng,
    latlng: { lat, lng }
  })

  setIsLoading(false)
}, [currentUserUID])

useEffect(() => {
  if (!isLoading) {
    // Only invoke new Firestore update when not already updating
    updateLocationInFirestore(latitude, longitude)
  }
}, [isLoading, latitude, longitude, updateLocationInFirestore])

如果你想在latitudelongitude變化時做不同的事情,你可以在你的組件中有多個useEffect掛鈎。 只需調整依賴數組即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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