在React中删除事件侦听器(lodash.throttle)

Seb*_*ian 10 javascript events javascript-events reactjs

嘿stackoverflowers,

removeEventListener()当我不使用throttle()lodash时工作.

   window.addEventListener('scroll', this.checkVisible, 1000, false);
     window.removeEventListener('scroll', this.checkVisible, 1000, false);
Run Code Online (Sandbox Code Playgroud)

(我绑定了构造函数中的方法)


不幸的是,throttle(this.checkVisible)功能缠绕它 - 不起作用.我认为这是因为当尝试删除监听器时,throttle()会生成新的实例,也许我应该全局绑定它.怎么样(如果是这样的话)?

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

谢谢,善意的人!

lag*_*one 14

Lodash trottle创建一个限制函数,因此您需要存储对它的引用才能删除eventlistener.

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

  • 这让我非常困扰,我也写了一篇有关它的博客文章-https://chipcullen.com/troubleshooting-adding-and-removing-eventlisteners/-再次感谢您,@ lagerone (3认同)