2

So, I have two stores. First pageStore serves business logic of specific page, and second globalStore logic of Android/iOS global events. When user enters specific page React.componentDidMount calls

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

so from this my pageStore started to listen global storage for GPS updates. But is there any way to disconnect listenTo on React.componentWillUnmount ?

4

2 回答 2

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
    }
});
于 2015-07-10T22:31:26.830 回答
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。

如果您查看此要点的第 60-68 行(https://gist.github.com/spoike/ba561727a3f133b942dc#file-reflux-js-L60-L68),请考虑 .listen 返回一个删除事件侦听器的函数。

在 componentWillUnmount 中,我们调用 this.unsubscribe 来移除监听器。您可以将 .listen 视为返回一个删除“侦听器”的函数,当 componentWillUnmount 生命周期发生时,我们调用该函数并终止侦听器。

Tl; dr:想象一下 .listen 附加一个侦听器并返回一个关闭侦听器的函数 - 当您第一次调用它时,侦听器打开,当您调用返回的函数时,它会关闭侦听器

于 2016-03-01T19:57:30.477 回答