【问题标题】:Load array of object with their id in : react native + firebase加载带有 ID 的对象数组:react native + firebase
【发布时间】: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()
  }

所以我想要这种行为:

  1. 在 componentDidMount 中,我开始了例程 --> 这有效
  2. loadPosts 正在使用 _getPostsFromDatabase() 函数加载 postids[] 数组 --> 这有效
  3. 然后,我创建了一个 for 循环来推送数组中的每个对象以设置最后的状态 --> FAIL

在第 3 步,一切正常,我制作了一些控制台日志进行调试,但存在一个巨大的实时问题,因为 evrything 是随机打印的。

如何在 for 循环结束时将我的 new_posts 填充数组设置为 setState。也许我对这种方法有误,或者如果我不是,我一定对 Async 函数有一些问题?

有没有专家可以帮助我更好地理解这种用例的内容?

谢谢

【问题讨论】:

    标签: javascript reactjs firebase react-native google-cloud-firestore


    【解决方案1】:

    基本上问题在于您试图以同步方式执行异步代码。 您的解决方案可能正在等待所有承诺解决。

    _loadPosts() {
    
        this._getPostsFromDatabase()
          .then(res => {
           let promises = res.map(id => {
             return firebase.firestore().collection("posts").doc(id)
                .get().then(doc => doc.data())
    
            })
        Promise.all(promises).then(res => {console.log(res);})
    
    
    
    
    
      }
    

    【讨论】:

    • 谢谢,它按预期工作。非常清楚 !我错过了地图功能和 Promise。
    【解决方案2】:

    您的控制台将在 for 循环之前记录,这就是您得到一个空数组的原因,只需在响应中包含您的控制台,就像这样:

     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 
                });
            }
            console.log(new_posts); ---->Include here
          })
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 2019-10-02
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多