简体   繁体   English

移除 React 中的事件监听器 (lodash.throttle)

[英]Removing event listener in React (lodash.throttle)

removeEventListener() works when I don't use throttle() from lodash. removeEventListener()在我不使用 lodash 中的 Throttle throttle()时起作用。

   window.addEventListener('scroll', this.checkVisible, 1000, false);
     window.removeEventListener('scroll', this.checkVisible, 1000, false);

(I bound the method in the constructor) (我在构造函数中绑定了方法)


Unfortunately, with the throttle(this.checkVisible) function wrapped around it - doesn't work.不幸的是,用throttle(this.checkVisible)函数包裹它 - 不起作用。 I assume it's because when trying to remove the listener, throttle() makes new instance and maybe I should bind it globally.我认为这是因为在尝试删除侦听器时,throttle() 会创建新实例,也许我应该全局绑定它。 How though (if that's the case)?但是如何(如果是这样的话)?

  import React from 'react';
    import throttle from 'lodash.throttle';
    
    class About extends React.Component {
      constructor(props) {
        super(props);
    
        this.checkVisible = this.checkVisible.bind(this);
      }
    
      componentDidMount() {
        window.addEventListener('scroll', throttle(this.checkVisible, 1000), false);
    
      }
    
      checkVisible() {
       if (window.scrollY > 450) {
        // do something
        window.removeEventListener('scroll', throttle(this.checkVisible, 1000),
        false);
        }
      }
    
      render() {
        return (
          <section id="about"> something
          </section>
        );
      }
    }
    
    export default About;

Lodash trottle creates a throttled function so you need to store a reference to it in order to remove the eventlistener. Lodash trottle 创建了一个受限制的函数,因此您需要存储对它的引用以删除事件侦听器。

import React from 'react';
import throttle from 'lodash.throttle';

class About extends React.Component {
  constructor(props) {
    super(props);

    this.checkVisible = this.checkVisible.bind(this);
    // Store a reference to the throttled function
    this.trottledFunction = throttle(this.checkVisible, 1000);
  }

  componentDidMount() {
    // Use reference to function created by lodash throttle
    window.addEventListener('scroll', this.trottledFunction, false);

  }

  checkVisible() {
   if (window.scrollY > 450) {
    // do something
    window.removeEventListener('scroll', this.trottledFunction, false);
    }
  }

  render() {
    return (
      <section id="about"> something
      </section>
    );
  }
}

export default About;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM