【问题标题】:How to detach onSnapshot Listener? <Cloud firestore>如何分离 onSnapshot 监听器? <云火库>
【发布时间】:2020-04-25 09:50:34
【问题描述】:

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

我的代码在这里:

// 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",

【问题讨论】:

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


    【解决方案1】:

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

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

    并在您的 componentWillUnmount 方法中添加

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

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多