firebase 尝试使用onSnapshot时不断出现错误

ttisahbt  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(91)

在REACT中尝试从firebase使用onSnapshot时,不断出现错误

TypeError: Object(...)(...).onSnapshot is not a function
(anonymous function)
C:/Users/\*\*/twitter-clone2/src/Feed.js:14
11 |  const \[posts, setPosts\] = useState(\[\]);
12 |
13 |  useEffect(() =\> {

14 |    collection(db,"posts").onSnapshot((snapshot) =\>
| ^  15 |      setPosts(onSnapshot.docs.map((doc) =\> doc.data()))
16 |    );
17 |  }, \[\]);

Firebase.js组件

//import firebase from 'firebase/compat/app'
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
    ****************************************
  };

  // Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);

  export { db };

Feed.js组件

import React, { useState, useEffect } from "react";
import TweetBox from "./TweetBox";
import Post from "./Post";
import "./Feed.css";
import { collection, onSnapshot } from "firebase/firestore"; 
import {db} from "./firebase"

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

  useEffect(() => {
    collection(db,"posts").onSnapshot((snapshot) =>
      setPosts(onSnapshot.docs.map((doc) => doc.data()))
    );
  }, []);

  return (
    <div className="feed">
      <div className="feed__header">
        <h2>Home</h2>
      </div>

      <TweetBox />

      
        {posts.map((post) => (
          <Post
            key={post.text}
            displayName={post.displayName}
            username={post.username}
            verified={post.verified}
            text={post.text}
            avatar={post.avatar}
            image={post.image}
          />
        ))}
      
    </div>
  );
}

export default Feed;
qni6mghb

qni6mghb1#

在最近的SDK中,onSnapshot是一个顶级函数,不再是Firestore对象上的方法。您可以从下面导入它的方式中看到这一点:

import { collection, onSnapshot } from "firebase/firestore";

所以要使用它,应该是:

useEffect(() => {
  onSnapshot(collection(db,"posts"), (snapshot) =>
    setPosts(onSnapshot.docs.map((doc) => doc.data()))
  );
}, []);

相关问题