【问题标题】:How to remove a Javascript EventEmiiter arrow function callback如何删除 Javascript EventEmiiter 箭头函数回调
【发布时间】:2023-04-10 19:51:01
【问题描述】:

我的 React 代码不断触发应该被删除的 EventEmitter 回调。当我检查扩展 EventEmiiter 的 React 类时,我发现回调仍然存在于 events 字段中,即使 removeListener 已经在这些回调上被调用。 p>

我怀疑这是因为我将回调添加到 EventEmitter 作为箭头函数,但是当我删除它们时,我没有。将它们作为箭头函数删除不起作用。在我下面的代码中,FirebaseStore 扩展了 EventEmitter:

  _onFirebaseChange() {
    this.setState({
      refId: this.getRefId()
    });
  }

  componentDidMount() {
    FirebaseStore.addChangeListener(() => this._onFirebaseChange());
  }

  componentWillUnmount() {
    FirebaseStore.removeChangeListener(this._onFirebaseChange);
  }

我需要使用箭头函数,因为更改事件 (_onFirebaseChange) 需要访问 this.state

当我从 Chrome 开发工具中查看源代码时,我很难确定 addChangeListenerremoveChangleListener 是否引用相同的回调:

key: 'componentDidMount',
value: function componentDidMount() {
  var _this2 = this;

  _FirebaseStore2.default.addChangeListener(function () {
    return _this2._onFirebaseChange();
  });
}
},{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
  _FirebaseStore2.default.removeChangeListener(this._onFirebaseChange);
}}

这是来自 Firebase 商店的相关代码:

addChangeListener(callback) {
    this.on(FIREBASE_CHANGE_EVENT, callback);
  }

  removeChangeListener(callback) {
    this.removeListener(FIREBASE_CHANGE_EVENT, callback);
  }
}

可以通过闭包来解决这个问题,但我认为这太过分了。

【问题讨论】:

  • ()=>foo()foo 不同 - 这与反应无关,因为这些功能不相等,因此 remove 找不到您想要删除的功能。有很多类似的帖子可以解决 JavaScript 中的其他事件,可能有人会找到很好的副本来做出反应。

标签: javascript reactjs events dom-events eventemitter


【解决方案1】:

更新您的 componentDidMount 方法。

componentDidMount() {
   FirebaseStore.addChangeListener(this._onFirebaseChange);
}

函数需要直接绑定。

【讨论】:

  • 这行不通 - 如果没有对上述代码的修改 - 因为我需要从 _onFirebaseChange 函数访问 this.state
【解决方案2】:

这是一个我应该早点发现的简单修复。 Alexi 发布的关闭解决方案也可以,但缺少的只是将 * _onFirebaseChange* 绑定到构造函数中的 this

所以在我的 React 类的构造函数中,我添加了这一行:

this._onFirebaseChange = this._onFirebaseChange.bind(this);

然后我的 componentDidMount 函数能够引用与 componentWillUnmount 相同的回调,同时也能够访问 this.state

  componentDidMount() {
    FirebaseStore.addChangeListener(this._onFirebaseChange);
  }

  componentWillUnmount() {
    FirebaseStore.removeChangeListener(this._onFirebaseChange);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多