Firebase快照在React TypeScript上不起作用。

huangapple go评论133阅读模式
英文:

Fireabase snapShot is not working on react typescript

问题

以下是您要翻译的内容:

我最近在学习React和Firebase。我遇到了这个问题,已经有2天了,但我还是无法解决它。当我从Firebase中检索数据时,使用snapShot时出现错误。

以下是代码:

const fetchData = async () => {
    const result = await getDocs(collection(db, "post"));

    onSnapshot(result, (snap: any) => {
        const newArray: any[] = [];
        snap.forEach((doc: any) => {
            if (doc !== newArray) {
                newArray.push({ title: doc.data().title, content: doc.data().content, user_id: doc.data().user_id, id: doc.id });
            }
        });
        setPost([...post, newArray]);
    });
}

以下是我的错误信息:

TS2769:没有匹配此调用的重载。最后一个重载产生了以下错误。
参数类型为'QuerySnapshot'无法分配给类型'Query'。
类型'QuerySnapshot'缺少类型'Query'的以下属性:converter、type、firestore、withConverter

请帮助我,我对TypeScript还很陌生(尽管我之前用过Angular,但React对我来说是相对较新的,Firebase也是)。

英文:

I am recently learning the React, and firebase. I've encountered this problem for like 2 days still I can't solve it. There is an error when I use snapShot from firebase when I am retrieving something.

Here is the code:

const fetchData = async () => {
      const result = await getDocs(collection(db, "post"))

      onSnapshot(result, (snap:any) => {
        const newArray:any[] = [];
        snap.forEach((doc:any) => {
            if(doc !== newArray){
              newArray.push({title: doc.data().title, content: doc.data().content, user_id:doc.data().user_id, id: doc.id})
            }
          });
          setPost([...post, newArray]);
      });
    }

Here is my error:

> TS2769: No overload matches this call. The last overload gave the
> following error.
> Argument of type 'QuerySnapshot<DocumentData>' is not assignable to parameter of type 'Query<unknown>'.
> Type 'QuerySnapshot<DocumentData>' is missing the following properties from type 'Query<unknown>': converter, type, firestore,
> withConverter

Please help me, I am new to Typescript (although I face angular before React is quite new to me, and so does firebase)

答案1

得分: 2

onSnapshot() 函数的第一个参数应该是 DocumentReferenceCollectionReference,但你正在传递一个 QuerySnapshot。在使用监听器之前,你不需要显式地获取文档。尝试以下代码:

const fetchData = async () => {
  const colRef = collection(db, "post");

  onSnapshot(colRef, (snap: any) => {
    // ... 处理响应
  });
}
英文:

The onSnapshot() function takes either a DocumentReference or a CollectionReference a first parameter but you are passing a QuerySnapshot. You don't have to fetch document explicitly before using a listener. Try:

const fetchData = async () =&gt; {
  const colRef = collection(db, &quot;post&quot;);

  onSnapshot(colRef, (snap: any) =&gt; {
    // ... handle response
  });
}

huangapple
  • 本文由 发表于 2023年3月9日 20:57:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定