Firestore-集合的React JS实时侦听器



Dears,请告知我如何保存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的东西)。

另请参阅:

  • 无法迭代从firebase中提取的用户数组
  • JSON对象的数组不为空,但不能使用foreach进行迭代,显示零长度
  • Firestore onSnapshot返回未定义

本次搜索的更多信息。

最新更新