反应如何在组件中正确删除列表器将卸载,为什么我需要在构造函数中绑定

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

本文关键字:为什么 卸载 绑定 构造函数 删除列 组件 删除 列表      更新时间:2023-09-26

我有点困惑,这个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:

bind() 方法创建一个新函数,该函数在调用时将其 this 关键字设置为提供的值,并在调用新函数时提供的任何参数序列之前具有给定的参数序列。

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