React 应用程序后端 firestore useEffect 无法正常工作

React app backend firestore useEffect not working correctly

我正在尝试跟踪我的网站使用 firestore 作为后端的访问者数量。

我的 useEffect 挂钩 getVistorCount 和 updateVistorCount 中有两个函数。 getVistorCount 从 firestore 获取包含 vistor_count 变量的文档,并将该数据数组保存到状态。

我的 updateVistorCount 函数获取我试图从状态更新的文档的 ID 和数据。问题是我的状态被初始化为一个空数组,所以当我尝试从状态获取 id 和 vistor_count 时,我收到错误“未捕获(承诺)TypeError:无法读取未定义的属性(读取 'id')" 因为来自 state 的数组是空的。

我还在 VSCode 中收到以下警告:“React Hook useEffect 缺少依赖项:'numberOfVistors' 和 'portfolioStatesRef'。要么包含它们,要么删除依赖项数组”

这是当前代码:

const portfolioStatesRef = collection(db, "portfolio-stats")
  
  useEffect (() => {

    let sessionKey = sessionStorage.getItem("sessionKey")
    
    const getVistorCount = async () => {
      const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)

      setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
         return  ({ ...doc.data(), id: doc.id })
      }))
    }

    const updateVistorCount = async () => {

      const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
      const updatedFields = {vistor_count: numberOfVistors[0].vistor_count + 1}
      await updateDoc(portfolioStatsDoc, updatedFields)
    }

    getVistorCount()
    
    if (sessionKey === null)
    {
      sessionStorage.setItem("sessionKey", "randomString")  
      updateVistorCount()
    }
    
    }, []) 

也许使用两种效果可以达到你想要的效果。最先获得访客:

useEffect (() => {

    let sessionKey = sessionStorage.getItem("sessionKey")
    
    const getVistorCount = async () => {
      const dataFromPortfolioStatsCollection = await getDocs(portfolioStatesRef)

      setnumberOfVistors(dataFromPortfolioStatsCollection.docs.map((doc) => {
         return  ({ ...doc.data(), id: doc.id })
      }))
    }

    getVistorCount()
    
 }, []) 

第二次更新计数

useEffect (() => {
    if(!numberOfVistors.length) return;

    const updateVistorCount = async () => {
      const portfolioStatsDoc = doc(db, "portfolio-stats", numberOfVistors[0].id)
      const updatedFields = {vistor_count: numberOfVistors[0].vistor_count + 1}
      await updateDoc(portfolioStatsDoc, updatedFields)
   }

   updateVistorCount()
    
 }, [numberOfVistors])