2017-10-13 49 views
0

我無法取消訂閱Firestore。ReactJS firestore無法取消快照

這裏是我的代碼:

import React from 'react'; 
    import { PropTypes } from 'react'; 
    import firebase from '../../common/firebase'; 
    import { Bar } from 'react-chartjs-2'; 
    import moment from 'moment'; 
    import s from './styles.css'; 
    import request from 'superagent'; 
    import Memoizer from '../../common/memoizer'; 
    class BasicChart extends React.Component { 

    firestore(){ 
     return firebase.firestore() 
    } 

    constructor(props){ 
     super(props); 
     this.memoizer = new Memoizer(); 
    } 

    dailyTransactions(){ 
     return this.memoizer.memoize(`daily_transactions`,() => { 
     return this 
      .firestore() 
      .collection(`daily_transactions`); 
     }) 
    } 

    todayDocument(){ 
     return this.memoizer.memoize(`todayDocument`,() => { 
      return this 
      .dailyTransactions() 
      .doc("2017-10-13"); 
     }); 
    } 

    listenRealtimeUpdate(){ 
     console.log("listening"); 
     this.todayDocument().onSnapshot(doc => { 
     console.log(this); 
     console.log(doc.data()); 
     }); 
    } 

    detach(){ 
     console.log("unsubscribing"); 
     const unsubscribe = this.todayDocument().onSnapshot(() => {}); 
     console.log(unsubscribe); 
     unsubscribe(); 
    } 

    render(){ 
     return (
     <div> 
      <button onClick={this.listenRealtimeUpdate.bind(this)}> LISTEN </button> 
      <button onClick={this.detach.bind(this)}> DETACH </button> 
     </div> 
    ) 
    } 
    } 

,但我仍然得到此警告。

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the MyChart component. 

我的猜測是造成問題,因爲我包裝的大多數事情到一個函數,但是,即使是在我memoized的財產,我還沒有從公司的FireStore快照拆卸組件suceeeded。

備忘錄,只是我的快速補丁庫做記憶,以便一個實例方法,總是會返回相同的對象。

回答

0

好的,這是我的錯,但我認爲說文檔有誤導性也是合理的,因爲分離是因爲你傳遞了一個空函數還是因爲你「呼叫」了快照實例。

基本上,問題是取消訂閱應該是該快照的同一個實例。

我記憶我的.listenRealTimeUpdate(),解決了我的問題,雖然在上面的例子中,並不是真正解決它的最好方法。

但在我真正的問題中,「分離」發生在.componentWillUnmount期間,所以它有點解決它自己。