从Firebase检索(allpost)数据并使用uid还要检索用户信息 [英] Retrieving (allpost) data from firebase and using uid want to retrieve user information also
问题描述
我想检索所有帖子,然后每个帖子都有一个uid,使用这个uid我想检索用户信息
I want retrieve all post then with each post there is a uid, using this uid i want to retrieve user information
我的代码是这样的,但是在随后的代码块中它不起作用并且状态没有改变
My code is like this but it is not working and state is not changing in then block
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 });
});
}
推荐答案
正如Josh所说,您没有处理所有 userInfo.once()
调用都是异步的事实.这意味着现在您的 this.setState({allPost:postAll,loading:false},)
调用会在 postAll.push(childData)
发生之前触发.通过添加一些 console.log
语句,您应该能够轻松地看到这一点.
As Josh commented, you're not handling the fact that all your userInfo.once()
calls are asynchronous. This means that right now your this.setState({ allPost: postAll,loading: false },)
call fires before the postAll.push(childData)
happen. You should be able to easily see this by adding some console.log
statements.
解决方案是使用 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 });
});
这篇关于从Firebase检索(allpost)数据并使用uid还要检索用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!