【问题标题】:Firestore - React JS realtime listener of a collectionFirestore - 集合的 React JS 实时监听器
【发布时间】:2021-10-05 07:28:14
【问题描述】:

亲爱的, 请告知如何保存 Firestore 请求的输出(请阅读以下代码中的评论):

const firestore = firebase.firestore();
export const fetchedTickets = []; //I want to store the fetched tickets from a collection "tickets" and use it somewhere else

//Starting to listen changes in Tickets collection
const unsubscriberForTicketsListener = firestore
  .collection("tickets")
  .onSnapshot((snapshot) => {
    snapshot.docChanges().forEach((change) => {
      if (change.type === "added") {
        // console.log("Added Ticket: ", change.doc.data());
        fetchedTickets.push(change.doc.data());
      }
      if (change.type === "modified") {
        console.log("Edited Ticket: ", change.doc.data());
      }
      if (change.type === "removed") {
        console.log("Remvoed Ticket: ", change.doc.data());
      }
    });

    console.log(fetchedTickets) //From here, I can reach the fetched tickets, but I can't return this array, or do something valuable with it (store, for example)
  });

console.log(fetchedTickets) //Here, fetchedTickets is just an empty array, so I can't return it's value to use it in a different file, for example

【问题讨论】:

  • 这是预期的行为。由于数据是从 Firestore 异步加载的,所有需要数据的代码都需要在回调中(就像你的第一个 console.log(fetchedTickets))。虽然回调之外的代码可以访问相同的变量,但它通常在数据加载之前运行 - 除非您自己确保它在正确的时间运行(通过使用 Promise 或类似 RxJS 的东西)。
  • 我不是反对者,但您可能要记住,以 ALL CAPS 输入的文本通常会被视为大喊大叫。

标签: reactjs google-cloud-firestore


【解决方案1】:

这是预期的行为。由于数据是从 Firestore 异步加载的,所有需要数据的代码都需要在回调中(比如你的第一个 console.log(fetchedTickets))。

虽然回调之外的代码可以访问相同的变量,但它通常在数据加载之前运行 - 除非您自己确保它在正确的时间运行(通过使用 Promise 或类似 RxJS 的东西)。

另见:

更多来自search

【讨论】:

  • 谢谢弗兰克。是的,我明白这一点,但我的问题是 - 我怎样才能从这个监听器的函数中取出获取的数据
  • 正如我的回答和链接中所解释的:这不是关于在特定范围内访问它,而是关于何时您访问它。当您的第二个 console.log(fetchedTickets) 运行时,数据尚未加载。让它等待的方法是用一个承诺,但此时你不妨使用get() 而不是onSnapshot
  • 是的,但是 get() 将返回一次数据,我想放置一个监听器,以便实时处理 firestore 中的所有更改
  • 这正是onSnapshot 的用途。但这确实意味着所有使用数据的代码都必须在 onSnapshot 回调中,否则它不会在正确的时间运行。
猜你喜欢
  • 2023-04-10
  • 2021-03-06
  • 2020-12-02
  • 2019-10-28
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2019-10-24
相关资源
最近更新 更多