React useEffect 没有从 Firestore 获取数据

时间:2021-05-05 14:51:21

标签: reactjs firebase google-cloud-firestore

我在 firestore 中有一个集合,我希望在我的 Reactjs 应用程序中呈现这些数据。 但是,不幸的是它没有从 firebase 获取任何数据。

反应代码:

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    db.collection("posts").onSnapshot((snapshot) => {
      setPosts(snapshot.docs.map((doc) => doc.data()));
    });
  }, []);
return (
    <div className="app">
      <div className="app__header">
        <img
          src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
          alt=""
        />
      </div>
      <h1>Hello World lets build Instagram</h1>
      <div className="app__body">
        {posts.map((post) => (
          <Post
            caption={posts.caption}
            imageUrl={posts.imageUrl}
            username={posts.username}
          />
        ))}
      </div>
    </div>
  );
}

Firebase Firestore 集合截图:

enter image description here

我不知道为什么它没有获取数据。 我交叉检查了 firebase 配置和代码:

const firebaseApp = firebase.initializeApp({
//config
});

const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();

export { db, auth, storage };

1 个答案:

答案 0 :(得分:2)

我认为这是一个错字:

        caption={posts.caption}
        imageUrl={posts.imageUrl}
        username={posts.username}

应该是:

        caption={post.caption}
        imageUrl={post.imageUrl}
        username={post.username}

(即没有“s”)。