如何取消订阅Firestore中的集合更改

时间:2019-04-26 08:19:38

标签: reactjs firebase redux google-cloud-firestore

我正在尝试退订Firestore中的变更侦听器,但无法使其正常工作。

根据Firebase文档,您需要调用onSnapshot()方法来停止监听。我想念什么?

https://firebase.google.com/docs/firestore/query-data/listen

这是调用订阅/取消订阅操作创建者的钩子:

useEffect(() => {
  subscribe()
  return () => {
    unsubscribe()
  }
}, [])

以下是订阅/取消订阅操作的创建者:

export const subscribe = () => {
  return (dispatch) => {    
    const items = db.collection('items')

    items.onSnapshot((snapshot) => {
      const data = snapshot.docs.map((item) =>  item.data())

      dispatch({ type: 'DO_SOMETHING', payload: data })
    })
  }
}

export const unsubscribe = () => {
  const items = db.collection('items')

  const unsubscribe = () => items.onSnapshot(() => {})

  unsubscribe()
}

谢谢!

1 个答案:

答案 0 :(得分:1)

在您的unsubscribe操作示例中,您创建了另一个侦听器并立即取消订阅,因此它不会影响subscribe操作中的侦听器。

export const subscribe = (setUnsubscribe) => {
  return (dispatch) => {    
    const items = db.collection('items')

    const unsubscribe = items.onSnapshot((snapshot) => {
      const data = snapshot.docs.map((item) =>  item.data())
      dispatch({ type: 'DO_SOMETHING', payload: data })
    });

    setUnsubscribe(unsubcsribe);
  }
}


// Component

useEffect(() => {
  let unsubscribe = () => {};
  subscribe((func) => { unsubscribe = func });
  return () => unsubscribe();
}, [])