javascript - 抓取所有帖子时如何抓取每个帖子的作者信息?

标签 javascript reactjs firebase react-native redux

发表帖子或评论时,只需通过 ID 添加用户作者。这样,当用户决定更新他们的头像/姓名等时,我不必找到他们曾经发表的每一篇帖子和评论并在那里更新。

enter image description here

当我只是抓取帖子并将它们作为有效负载传递(没有作者信息)时,它工作正常,没有错误:

export const fetchPostsByNewest = () => {
  return (dispatch) => {
    firebase.database().ref('/social/posts')
      .on('value', snapshot => {
          dispatch({ type: NEW_POSTS_FETCH_SUCCESS, payload: snapshot.val() });
       };
    };
};

我尝试过像这样获取作者信息,但我无法找出如何在一个有效负载中完成所有操作的解决方案:

export const fetchPostsByNewest = () => {
  return (dispatch) => {
    firebase.database().ref('/social/posts').on('value', postSnapshot => {
        const posts = postSnapshot.val();

        const postsAsArray = Object.keys(posts).map(postId => posts[postId]);
        postsAsArray.forEach(post => {
            const postWithUser = {};

            Object.keys(post).forEach(key => {
              postWithUser[key] = post[key];
            });

            const userId = post.author;

            firebase.database().ref(`/social/users/${userId}`).once('value', userSnapshot => {
              const profile_info = userSnapshot.val();

              postWithUser.profile_info = profile_info.profile_info;

              console.log(postWithUser);

                dispatch({ type: NEW_POSTS_FETCH_SUCCESS, payload: postWithUser });
            });
        });
      });
  };
};

这些是我从上面获得的控制台日志:

enter image description here

这似乎带来了正确的数据,但我刚刚收到此错误:

enter image description here

你能给我一些建议吗,这让我发疯!

谢谢!

最佳答案

根据 Firebase API once() 返回一个 Promise,因此您的代码应该或多或少类似于:

firebase.database().ref(`/social/users/${userId}`).once('value').then(userSnapshot => {
  const profile_info = userSnapshot.val();
  postWithUser.profile_info = profile_info.profile_info;

  console.log(postWithUser);

  dispatch({ type: NEW_POSTS_FETCH_SUCCESS, payload: postWithUser });
});

以下是对文档的引用:https://firebase.google.com/docs/reference/node/firebase.database.Reference#once

关于javascript - 抓取所有帖子时如何抓取每个帖子的作者信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772837/

相关文章:

javascript - PHP 从下拉列表中获取文本

javascript - 以编程方式刷新所有客户端浏览器中的局部 View

javascript - 如何使用护照检查 react 组件上的isAuthenticated

javascript - React SSR Firebase 应用程序中的图像

firebase - Dart null与Null

javascript - 如果语句为空字符串则运行

javascript - 如何在 CoffeeScript 中定义全局变量?

reactjs - ReactJS、TypeScript 中的数组动画

android - 尝试在 Firebase 测试实验室中调用虚方法 android.arch.lifecycle.Lifecycle

firebase - 如何在 Firebase 上禁用 Crashlytics 电子邮件通知?