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

React how to remove listners correctly in componentWillUnmount, why do I need the bind in the constructor?

我有点懵,这个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.

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