2015-07-10 34 views
2

所以,我有兩個商店。第一個pageStore服務於特定頁面的業務邏輯,以及第二個Android/iOS全局事件的globalStore邏輯。 當用戶進入特定頁面React.componentDidMount調用斷開回流listenTo方法

pageEntered: function() { 
    this.listenTo(globalStore, this.locationUpdated); 
}, 

所以從這個我pageStore開始聽GPS更新全局存儲。但有沒有辦法斷開React.componentWillUnmount上的listenTo?

回答

2

這裏有一個例子,如何從一家商店監聽(來自官方的例子取)退訂:

var Status = React.createClass({ 
    getInitialState: function() { }, 
    onStatusChange: function(status) { 
     this.setState({ 
      currentStatus: status 
     }); 
    }, 
    componentDidMount: function() { 
     this.unsubscribe = statusStore.listen(this.onStatusChange); 
    }, 
    componentWillUnmount: function() { 
     this.unsubscribe(); 
    }, 
    render: function() { 
     // render specifics 
    } 
}); 
0

下面就來想想發生的事情在上面的例子中的一種方式:

var myFunc = function(){ 
    console.log("This gets fired immediately"); 
    var randomNumber = Math.ceil(Math.random()*10); 
    return function() { 
     return randomNumber; 
    } 
} 

var a = myFunc(); //Console log fires IMMEDIATELY, a is the returned function 

a(); //some integer from 1 to 10 

由於當我們將它分配給一個變量時,myFunc被調用,console.log立即觸發 - 它就像this.unsubscribe = statusStore.listen(this.onStatusChange);一旦componentDidMount發生,立即「打開」偵聽器。

在componentDidMount生命週期方法中,我們將一個偵聽器附加到使用.listen。這被調用。爲了方便起見,我們將函數的結果分配給this.unsubscribe。

如果你看看這個要點(https://gist.github.com/spoike/ba561727a3f133b942dc#file-reflux-js-L60-L68)的線60-68想。聽返回功能,消除事件偵聽器。

在componentWillUnmount,我們調用this.unsubscribe從而消除聽者。您可以將.listen視爲返回一個刪除「偵聽器」的函數,並且當componentWillUnmount生命週期發生時,我們調用該函數並終止偵聽器。

鉈;博士:想象。聽附加一個監聽器,並返回關閉listener--當你第一次調用它的監聽器,當你調用被返回的功能,它將關閉監聽功能