【问题标题】:ComponentWillUnmount to unsubscribe from FirestoreComponentWillUnmount 取消订阅 Firestore
【发布时间】:2019-04-29 14:42:32
【问题描述】:

我正在尝试使用 ComponentWillUnmount 停止侦听 Firebase Firestore 集合更改:

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

var unsubscribe = db.collection("cities")
    .onSnapshot(function (){
      // Respond to data
      // ...
    });

// Later ...

// Stop listening to changes
unsubscribe();

但是,我无法访问此 unsubscribe();因为它是在 ComponentWillMount 中声明的,我需要在 ComponentWillUnmount 中使用它。

如何在 ComponentWillUnmount 中使用这个 unsubscribe()?如果我尝试将其保存在状态中,则会引发取消订阅不是函数的错误。

  constructor() {
    super();
    this.state = {
      notes: [],
      unsubscribe: null
    };
    this.getNotes = this.getNotes.bind(this);
  }

  componentDidMount(){
    this.getNotes();
  }

  componentWillUnmount(){
    var unsubscribe = this.props.unsubscribe;
    unsubscribe();
  }

  getNotes = () => {
    const db = this.props.firestore;
    const colRef = db.collection("users").doc(this.props.uid)
    .collection("notes");

    let notes = [];
    const that = this;

    // Realtime updates listener
    var unsubscribe = colRef.orderBy("timestamp", "asc")
    .onSnapshot(function(querySnapshot) {
        var notes = [];
        querySnapshot.forEach(function(doc) {
            notes.push(
              { id: doc.id,
                body: doc.data().body}
                );
        });
        that.setState({ notes })
    });

    this.setState({ unsubscribe })
  }

投掷:

Uncaught TypeError: unsubscribe is not a function

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    您可以将取消订阅引用保存在类实例 (this) 上:而不是执行 var unsubscribe 执行 this.unsubscribe = [...] 稍后再次从类实例中读取它:this.unsubscribe()

    componentDidMount(){
      this.getNotes();
    }
    
    componentWillUnmount(){
      this.unsubscribe();
    }
    
    getNotes = () => {
      const db = this.props.firestore;
      const colRef = db.collection("users").doc(this.props.uid)
      .collection("notes");
    
      let notes = [];
      const that = this;
    
      // Realtime updates listener
      this.unsubscribe = colRef.orderBy("timestamp", "asc")
      .onSnapshot(function(querySnapshot) {
          var notes = [];
          querySnapshot.forEach(function(doc) {
              notes.push(
                { id: doc.id,
                  body: doc.data().body}
                  );
          });
          that.setState({ notes })
      });
    }
    

    【讨论】:

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