【问题标题】:React function does not await data from FirestoreReact 函数不等待来自 Firestore 的数据
【发布时间】:2023-01-27 00:27:15
【问题描述】:

每次我运行以下代码时,React 似乎都在继续,而不是像我在 setCurrentDevice 中要求的那样填充 CurrentDevice。当在最后一行询问时,它只是在日志中抛出一个 undefined 。它似乎确实记录了正确的设备详细信息,正如我在第一个 console.log 运行时看到的那样。在继续之前如何使反应填充状态 CurrentDevice?

const q = query(collection(db, 'DeviceDetails'), where('serialNo', '==', SerialNo))

    const querySnapshot = await getDocs(q)
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      setCurrentDevice(doc.data());
      console.log(doc.data());
    })

    console.log(currentDevice);

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    在本例中,当您将 hook 更新为 useState 时,component 使用 hook 的新 value 重新渲染,因此 currentDevice 将在下一次渲染期间获得新的 value 它不可用然而。尝试从你的jsxconsol.log('this is a new render and this is my data : ',currentDevice)来更好地理解

    【讨论】:

    • 问题是,我需要在下面几行中使用 currentDevice 来检查 currentDevice 是否具有与表单中输入的详细信息相同的详细信息。那么有没有办法让它等待,以便我可以执行该检查?
    猜你喜欢
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多