【问题标题】:Retrieving (allpost) data from firebase and using uid want to retrieve user information also从firebase检索(allpost)数据并使用uid也想检索用户信息
【发布时间】:2020-02-03 23:33:24
【问题描述】:

我想检索所有帖子然后每个帖子都有一个uid,使用这个uid我想检索用户信息

我的代码是这样的,但它不工作并且状态在 then 块中没有改变

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 });
    });
  }

【问题讨论】:

  • 问题是你在forEach中运行异步调用,这是同步的。

标签: reactjs firebase firebase-realtime-database


【解决方案1】:

正如 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 });
});

【讨论】:

  • Frank van Puffelen,非常感谢你这对我来说很好,你救了我的命。
猜你喜欢
  • 1970-01-01
  • 2021-02-03
  • 2018-12-06
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多