【问题标题】:Redux: Unsubscribing a listener inside that listener is not workingRedux:取消订阅该侦听器内部的侦听器不起作用
【发布时间】:2021-03-29 03:33:54
【问题描述】:

我有一个监听器函数来监听存储变化。

unsub = store.subscribe(gameListener);

gameListener 函数如下所示:

const gameListener = () => {
  // getting gameState from store...

  if (gameState.hasGameStarted) {
    startGame();
    unsub();
  }
}

即使我正在调用unsub 方法,侦听器也没有被取消订阅。问题是当我将unsub() 放在if 语句之外时,它正在工作。知道为什么会这样吗?

请注意,条件会在某个时候变为true,并且我已验证该控件位于if 语句中。

【问题讨论】:

    标签: javascript redux listener


    【解决方案1】:

    由于unsubscribe函数是在你注册gameListener为订阅者后才返回的,所以你不能在gameListener里面定义unsub(),如果你订阅后重新定义它不是同一个函数。

    但是,您可以定义一个外部对象,我们将其称为 ref(从反应钩子中获取页面),在 gameListener 函数中使用它,并在创建后更新 ref 的 unsub 函数。

    const ref = {};
    
    const gameListener = () => {
      // getting gameState from store...
    
      if (gameState.hasGameStarted) {
        startGame();
        ref.unsub();
      }
    };
    
    const unsub = store.subscribe(gameListener);
    
    ref.unsub = unsub;
    

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2018-12-12
      • 1970-01-01
      • 2020-11-09
      • 2021-03-16
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多