如何分离onSnapshot Listener? <Cloud Firestore>

时间:2020-04-25 09:50:34

标签: firebase react-native google-cloud-firestore

我已经使用react native开发了我的应用程序,并将Cloud Firestore用于数据库。
我想在用户注销之前分离快照侦听器。
如何在unSubscribe();而非getDataComponent中执行signOutComponent

我的代码在这里:

// getDataComponent.js
class DataComponent extends React.Component {
  getData(year) {
    const { currentUser } = firebase.auth();
    const db = firebase.firestore();
    const docRef = db.collection(`users/${currentUser.uid}/statics`).doc(`${year}`);
    const unSubscribe = docRef.onSnapshot((doc) => {
      // ...
    }, (err) => {
      // ...
    });
  }
  render() {
    return (
      // ...
    );
  }
}
// signOutComponent.js
class signOut extends React.Component {
  signOut() {

    // I'd like to detach snapshot listner here.

    firebase.auth().signOut()
      .then(() => {
        console.log('signOut success');
      })
      .catch((error) => {
        // ...
      });
  }
  render() {
    return (
      // ...
    );
  }
}

我的环境:

"expo": "^34.0.0",
"react": "16.8.3",
"react-native": "https://github.com/expo/react-native/archive/sdk-34.0.2.tar.gz",
"firebase": "^7.14.1",

1 个答案:

答案 0 :(得分:1)

onSnapshot函数返回取消订阅函数。 你可以做

this.unsubscribe = ref.onSnapshot(...)

,然后在您的componentWillUnmount方法中添加

if(this.unsubscribe) {
this.unsubscribe();
}