首页 > 解决方案 > 删除 Firestore 中的文档不更新 onSnapshot

问题描述

我正在从 firestore 中获取 react native 的项目列表。

如果更新了项目文档,我的列表会通过 onSnapshot 按预期刷新。但是如果文档被删除,我的列表不会刷新。

有没有办法让我捕获已删除的文档?

this.unsubscribe = firebase.firestore().collection('bigItems').doc(id)
                  .collection('littleItems').onSnapshot(this.getItems)

   getItems = (querySnapshot) => {
     const items = [];

    querySnapshot.forEach((doc) => {
      firebase.firestore().collection('events').doc(doc.id).get()
        .then(item => {
            const { id } = item.data();
            items.push({
              id: item.id
            });
            this.setState({
              items: items,
              loading: false,
           });
        })
        .catch(function (err) {
          return err;
        });
    })
  }

标签: react-nativegoogle-cloud-firestore

解决方案


尝试以下方法是否适合您:

const dataRef = firebase.firestore()
            .collection('bigItems').doc(id)
            .collection('littleItems').onSnapshot(res => {

            // Listen to change type here
            res.docChanges().forEach(change => {

            const docName=change.doc.id;
            const docData=change.doc.data();

            // Refer to any field in the document like:
            // E.g. : data.name, data.text etc.
            // i.e. (whatever fields you used for the document)

            if (change.type === "added") {
                // Append to screen
            }
            if (change.type === "removed") {
                // Now, Manually remove from UI
                // Data from state before snapshot is still here,
                // use some reference in data to remove from screen.
            }
        });
    });

推荐阅读