如何在componentWillUnmount中正确删除列表器,为什么我需要在构造函数中绑定?

dan*_*lla 6 javascript event-listener addeventlistener reactjs

我有点困惑,这个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);
  }
Run Code Online (Sandbox Code Playgroud)

还有这个:

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

我担心的是第二种语法没有正确删除列表器,它会导致此警告:

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.
Run Code Online (Sandbox Code Playgroud)

Rad*_*nik 11

重要:

a.bind(this) !== a.bind(this) 
Run Code Online (Sandbox Code Playgroud)

MDN称:

绑定()方法创建一个新的功能,调用它时,具有其将此关键字设置为所提供的值,与前述的当新功能被调用任何设置参数给定的序列.

您的第一种方法会覆盖this.togglePaneHelper新的绑定函数.第二个删除比它加入不同的事件侦听器的功能-既addEventListenerremoveEventListener必须得到相同的基准功能.