【发布时间】:2020-04-19 11:14:30
【问题描述】:
我来自 C++、C、Python 领域,我是反应原生/JS/后端世界的新手。
我在从 firebase 加载数据时遇到了一些问题。这是我想要的:
我的数据库:
- 用户:uid:postids[]
- 帖子:postids:内容
我想从用户加载 postids[] 数组,然后加载该数组中每个 postids[] 的内容(根据 postids[] 数组中的每个 postids)。
这是我的代码:
_getPostsFromDatabase() {
var docRef = firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid);
return docRef.get().then(function(doc) {
if (doc.exists) {
return doc.data()["posts"];
}
}).catch(function(error) {
alert("Error getting document:", error);
});
}
_loadPosts() {
var new_posts = [];
this._getPostsFromDatabase()
.then(res => {
var i;
for (i = 0; i < res.length; i++) {
firebase.firestore().collection("posts").doc(res[i])
.onSnapshot(function(doc) {
new_posts.push(doc.data());
console.log(new_posts); --> This line print correct data
});
}
})
.catch(error => console.log(error));
console.log(new_posts); ---> This line print an empty array
}
componentDidMount() {
this._loadPosts()
}
所以我想要这种行为:
- 在 componentDidMount 中,我开始了例程 --> 这有效
- loadPosts 正在使用 _getPostsFromDatabase() 函数加载 postids[] 数组 --> 这有效
- 然后,我创建了一个 for 循环来推送数组中的每个对象以设置最后的状态 --> FAIL
在第 3 步,一切正常,我制作了一些控制台日志进行调试,但存在一个巨大的实时问题,因为 evrything 是随机打印的。
如何在 for 循环结束时将我的 new_posts 填充数组设置为 setState。也许我对这种方法有误,或者如果我不是,我一定对 Async 函数有一些问题?
有没有专家可以帮助我更好地理解这种用例的内容?
谢谢
【问题讨论】:
标签: javascript reactjs firebase react-native google-cloud-firestore