【问题标题】:Read Data from Firebase and save it into an Array - React从 Firebase 读取数据并将其保存到数组中 - React
【发布时间】:2021-09-20 16:57:32
【问题描述】:
我只是想不通为什么我不能将加载的数据保存到数组中。
我正在尝试在数据完全加载后将数据推送到数组中(在 then() 内)
知道为什么它不起作用吗?
非常感谢:)
useEffect(() => {
fetchData = async () => {
let tempArray = [];
await firebase.firestore().collection('users').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
firebase.firestore().collection('users').doc(doc.id).collection('posts').get().then((snapShot) => {
snapShot.forEach((newDoc) => {
tempArray.push({
id: doc.id,
data: newDoc.data()
})
})
})
})
})
console.log(tempArray) // Output: Array []
}
fetchData();
}, [])
【问题讨论】:
标签:
reactjs
firebase
react-native
google-cloud-firestore
use-effect
【解决方案1】:
.forEach 不是异步的 - 它不会等待您的内循环 .get()s。您需要执行以下操作:
await firebase.firestore().collection('users').get().then((querySnapshot) => {
Promise.all(querySnapshot.map((doc) => {
firebase.firestore().collection('users').doc(doc.id).collection('posts').get().then((snapShot) => {
snapShot.forEach((newDoc) => {
tempArray.push({
id: doc.id,
data: newDoc.data()
})
})
})
})
)
})
此外-这似乎非常低效-因为您要获取所有用户和他们的所有帖子,所以您可以只使用一个collectionGroup是一次往返,然后如果您需要排序,请按.parent排序(您在所提供的示例中没有表现出任何此类需求)
await firebase.firestore()..collectionGroup('posts').get().then((querySnapShot) => {
querySnapShot.forEach((newDoc) => {
tempArray.push({
id: doc.id,
data: newDoc.data()
})
})
})
最后,您将async/await 与.then() 语法混合在一起,通常不建议这样做:
// .get() is asynchronous
const querySnapShot = await firebase.firestore()..collectionGroup('posts').get();
// push() is synchronous, so need for await
querySnapShot.forEach((newDoc) => {
tempArray.push({
id: doc.id,
data: newDoc.data()
})
})