【问题标题】:Disconnect Reflux listenTo method断开回流的listenTo方法
【发布时间】:2015-09-29 12:58:42
【问题描述】:

所以,我有两家商店。第一个 pageStore 服务于特定页面的业务逻辑,第二个 globalStore 服务于 Android/iOS 全局事件的逻辑。 当用户进入特定页面时 React.componentDidMount 调用

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

因此,我的 pageStore 开始监听全球存储以获取 GPS 更新。但是有什么方法可以断开 React.componentWillUnmount 上的 listenTo 吗?

【问题讨论】:

    标签: reactjs refluxjs


    【解决方案1】:

    有一个如何取消订阅商店监听的示例(取自官方示例):

    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
        }
    });
    

    【讨论】:

      【解决方案2】:

      这是思考上例中发生的事情的一种方式:

      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 行,请考虑 .listen 返回一个删除事件侦听器的函数。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-29
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 2017-04-18
        • 2015-05-02
        相关资源
        最近更新 更多