javascript - 在 React 组件卸载时删除事件监听器

标签 javascript reactjs addeventlistener

我在我的一个组件中监听窗口“滚动”事件。然而,当组件被卸载时,滚动事件监听器并没有被移除。

卸载组件后发生滚动事件时会产生以下错误:

warning.js:36 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 TopNavDesktop component.

如何正确删除此事件监听器?

示例代码:

class NavBar extends Component {
  constructor() {
    super();

    this.state = {
      distanceScrolled: null
    }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll.bind(this));
  }

  handleScroll(e){
    const distanceScrolled = e.srcElement.body.scrollTop;

    this.setState({ distanceScrolled: distanceScrolled });
  }

  render { ... } 
}

最佳答案

当您删除监听器时,您正在创建一个新的函数引用。

someFn.bind(this) === someFn.bind(this) 将计算为 false。

相反,将函数保存在构造函数中并使用该引用:

class NavBar extends Component {
  constructor() {
    super();

    this.state = {
      distanceScrolled: null
    }

    this.scrollFn = this.handleScroll.bind(this);
  }

  componentDidMount() {
    window.addEventListener('scroll', this.scrollFn);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollFn);
  }

  handleScroll(e){
    const distanceScrolled = e.srcElement.body.scrollTop;

    this.setState({ distanceScrolled: distanceScrolled });
  }

  render { ... } 
}

关于javascript - 在 React 组件卸载时删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165169/

相关文章:

reactjs - 项目中如何升级ant-design?

JavaScript倒计时弹出窗口

javascript - eventListener 内的代码没有立即调用?

javascript - 在 JavaScript 中通过 ADODB 从 Access DB 构建 HTML 表

javascript - 为什么 2.23 + 0.17 = 2.4899999999999998 在 JavaScript 中?

reactjs - 为什么在 nextjs Link 中使用标签?

javascript - event.altKey on the keyup event is false though the key is "down"

javascript - 添加一个插入 javascript 的按钮到收藏夹

javascript - 如何在 jQuery 中看到目标 div 时突出显示 anchor 链接?

reactjs - 我如何在docker容器中从我的React构建中提供静态文件