【问题标题】:Property 'onSnapshot' does not exist on type 'CollectionReference<DocumentData>'属性 \'onSnapshot\' 在类型 \'CollectionReference<DocumentData>\' 上不存在
【发布时间】:2023-01-19 18:39:53
【问题描述】:

我正在尝试获取指定集合中的所有文档。但是,我似乎无法让它工作。

 useEffect(() => {
    const routineRef = collection(db, "routines", session?.user?.id!, currentRoutine.name);
    routineRef
      .onSnapshot((docsSnap: any) => {
        setWeightsHistorySnapshot(docsSnap.docs);
        console.log("Current data: ", docsSnap.docs);
      })
      .then((unsub: () => any) => {
        return () => unsub();
      });

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    在 firebase 的第 9 版中,他们将 onSnapshot 更改为您导入的顶级函数,而不是集合的属性。此外,onSnapshot 不会返回承诺,因此您的.then 将无法正常工作。

    v9 中的正确代码如下所示:

    import { collection, onSnapshot } from 'firebase/firestore',
    // ...
    
    useEffect(() => {
      const routineRef = collection(db, "routines", session?.user?.id!, currentRoutine.name);
      const unsubscribe = onSnapshot(
        routineRef,
        (docsSnap: any) => {
          setWeightsHistorySnapshot(docsSnap.docs);
          console.log("Current data: ", docsSnap.docs);
        }
      )
      return unsubscribe;
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2021-01-09
      • 2021-07-10
      相关资源
      最近更新 更多