繁体   English   中英

React function 不等待来自 Firestore 的数据

[英]React function does not await data from Firestore

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

当您在此示例中将hook更新为useState时, component会使用hook的新value重新渲染,因此currentDevice将在下一次渲染期间获得新value ,但它尚不可用。 尝试从您的 jsx 内部jsx consol.log('this is a new render and this is my data: ',currentDevice)以更好地理解。

另请注意,在您的代码中,您只将querySnapshot的最后item存储在currentDevice中,而不是所有items ,因为在每次迭代中您都会覆盖该值,因此它只会以最后一个结束,我不知道是什么你正在尝试做,但我认为这不是你想要实现的,如果你想将它们全部存储,这是正确的方法

const querySnapshot = await getDocs(q)
setCurrentDevice(querySnapshot.map((doc) => doc.data()));

但是如果你真的只想存储最后item更好地这样做:

const querySnapshot = await getDocs(q);
setCurrentDevice(querySnapshot[querySnapshot.length- 1].data());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM