我想检索所有帖子,然后每个帖子都有一个uid,使用这个uid我想检索用户信息
我的代码是这样的,但是在随后的代码块中它不起作用并且状态没有改变
getAllPost(){
let allPost = firebase.database().ref("all-post");
let postAll = [];
allPost.once("value").then(data => {
data.forEach(function (childSnapshot) {
let childData = childSnapshot.val();
childData.postId = childSnapshot.key;
let userInfo = firebase.database().ref(`users/${childData.uid}`);
userInfo.once("value").then(data => {
childData.userInfo = data;
postAll.push(childData);
})
})
}).then(()=>{
this.setState({ allPost: postAll,loading: false },);
}).catch(err => {
this.setState({ loading: false });
});
}
答案 0 :(得分:2)
正如Josh所评论的那样,您没有处理所有userInfo.once()
调用都是异步的事实。这意味着现在您的this.setState({ allPost: postAll,loading: false },)
呼叫会在postAll.push(childData)
发生之前触发。通过添加一些console.log
语句,您应该能够轻松地看到这一点。
解决方案是使用Promise.all()
等到所有加载完成:
let allPost = firebase.database().ref("all-post");
let postAll = [];
allPost.once("value").then(data => {
let promises = [];
data.forEach(function (childSnapshot) {
let childData = childSnapshot.val();
childData.postId = childSnapshot.key;
let userInfo = firebase.database().ref(`users/${childData.uid}`);
promises.push(
userInfo.once("value").then(data => {
childData.userInfo = data;
postAll.push(childData);
})
})
})
return Promise.all(promises);
}).then(()=>{
this.setState({ allPost: postAll,loading: false },);
}).catch(err => {
this.setState({ loading: false });
});