javascript - React 如何在 componentWillUnmount 中正确移除监听器,为什么我需要在构造函数中绑定(bind)?

标签 javascript reactjs addeventlistener event-listener

我有点困惑,这个sintax有什么区别:

  constructor(props) {
    super(props);
    this.state = {
      openPane: false
    }
    this.togglePaneHelper = this.togglePaneHelper.bind(this);
  }
  componentDidMount() {
    document.body.addEventListener('click', this.togglePaneHelper);
  }
  componentWillUnmount() {
    document.body.removeEventListener('click', this.togglePaneHelper);
  }

还有这个:

  constructor(props) {
    super(props);
    this.state = {
      openPane: false
    }
  }
  componentDidMount() {
    document.body.addEventListener('click', this.togglePaneHelper.bind(this));
  }
  componentWillUnmount() {
    document.body.removeEventListener('click', this.togglePaneHelper);
  }

我担心的是第二种语法没有正确删除监听器,它导致了这个警告:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

最佳答案

重要提示:

a.bind(this) !== a.bind(this) 

根据 MDN :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

您的第一种方法使用新的绑定(bind)函数覆盖 this.togglePaneHelper。第二个删除了与添加时不同的事件监听器函数 - addEventListenerremoveEventListener 必须获得相同的函数引用

关于javascript - React 如何在 componentWillUnmount 中正确移除监听器,为什么我需要在构造函数中绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223918/

相关文章:

javascript - 如何防止 componentWillUpdate 导致无限循环?

javascript - 为什么 document.addEventListener ('load' , function) 在 greasemonkey 脚本中不起作用?

javascript - 在具有各种监听器的 for 循环中使用 addEventListener()

javascript - JavaScript 值中的小写字母和单词合并在一起

javascript - 如何处理 Controller 内部 Angular 服务的错误?

javascript - 通过 Json 存储和加载 JavaScript 变量

javascript - 从 DOM 中删除元素时保持 reactjs 元素状态

javascript - react-redux-i18n 切换语言

javascript 日期验证

javascript - 如何在 addEventListener 方法之外访问变量值?