提问者:小点点

Window.RemoveEventListener不在componentWillUnmount上工作


这是我的代码,在组件中使用,但是当我路由到另一个URL时,控制台给我错误-

错误

警告:无法对未装入的组件执行React状态更新。 这是一个no-op,但它表示您的应用程序中存在内存泄漏。 若要修复,请取消componentWillUnmount方法中的所有订阅和异步任务。


  componentDidMount = async () => {
   // await myAPI call
   window.addEventListener("scroll", this.onWindowscroll);
  }

  onWindowscroll = async () => {
    console.log('onWindowscroll);
    // await myAPI call when scroll reach to bottom.
  }

  componentWillUnmount = () => {
    window.removeEventListener('scroll', this.onWindowscroll);
    console.log('componentWillUnmount H');
  }


不知道为什么会这样! 当我硬刷新并转到任何其他路由时,就会出现此错误。 因为我使用的是箭头函数,所以在挂载时不需要使用.bind


共1个答案

匿名用户

componentDidMount()
{
   this.onWindowscroll();
    window.addEventListener("scroll", this.onWindowscroll);
}

 onWindowscroll = async () => {
    console.log('onWindowscroll);
}

componentWillUnmount()
{
window.removeEventListener('scroll', this.onWindowscroll);
    console.log('componentWillUnmount');

}

您必须将与第二个参数相同的函数传递给AddEventListener/RemoveEventListener。 当您传递this.onWindowsCroll.bind(this)时,您实际上是在创建一个新函数,因此这两个函数并不相同。箭头表示法,将this保留为类的this,然后您可以两次发送对同一函数的引用。