【问题标题】:JavaScript/TypeScript - Callback not removed, why?JavaScript/TypeScript - 未删除回调,为什么?
【发布时间】:2023-01-15 08:54:50
【问题描述】:

同事们,我可以用日志证明,在某些公共组件中删除监听器是行不通的。首先,我看到监听器仍然被调用,其次,我从来没有看到第二个控制台输出,这让我更加困惑。

const scanListeners = []
...
function removeListener(callback) {
    console.log("About to remove listener")
    scanListeners = scanListeners.filter(listenerCallback => listenerCallback !== callback)
    console.log("Listener removed")
}

这可以用一些 JavaScript 细节来解释吗?我不是 JS 的专家,但仍然工作了几年,但我仍然无法解释会发生什么。

BETWEEN 组件在 React Native 环境中调用,如下所示:

const listener: Component.callBack = (code) => {
    processCode(code)
    dispatch(fetchList(code));
    try {
      Component.removeListener(listener);
    }
    catch { }
  };

附言监听器添加代码:

function addScanListener(callback) {
  const listenerAlreadyExists = scanListeners.some(listenerCallback => listenerCallback === callback)
  if (!listenerAlreadyExists) {
      scanListeners.push(callback)
  }
}

【问题讨论】:

  • 如果您使用的是命名函数,则应该通过.removeEventListeners 删除监听器,而不是像那样设置数组引用
  • console.log("Listener removed) 关闭报价试试?
  • function removeListener 与您作为 Component.removeListener(listener); 调用的方法并不完全相同。请提供完整的minimal reproducible example,同时包括将listener放在scanListeners中的代码
  • 添加了添加侦听器的代码。我的回调是一个匿名函数。
  • 您要将听众添加到什么?因为在这里您只删除了对添加到数组中的侦听器的引用。如果这些不是标准的事件侦听器,您能解释一下它们是什么吗?

标签: javascript typescript react-native


【解决方案1】:
const scanListeners = []
...
function removeListener(callback) {
    console.log("About to remove listener")
    scanListeners = scanListeners.filter(listenerCallback => listenerCallback !== callback)
    console.log("Listener removed")
}

在这种情况下,您正在尝试重新分配常数多变的。

【讨论】:

  • 哦,是的。这就是原因!谢谢,你的观察是关键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 2022-12-23
  • 1970-01-01
相关资源
最近更新 更多