2016-02-17 36 views
1

删除窗口上的事件侦听器不起作用,就好像它在添加和删除时不是相同的功能一样。有关如何解决这个问题的想法?我也尝试在文件之外的类和上面抽象onScroll方法,也没有运气。reactjs removeListener不能与es6类一起使用

componentDidMount() { 
    if (__CLIENT__) { 
     window.removeEventListener('scroll', this.onScroll.bind(this), true); 
     console.log('mounting') 
     window.addEventListener('scroll', this.onScroll.bind(this), true); 
    } 
    } 

    componentWillUnmount() { 
    console.log('unmount'); 
    if (__CLIENT__) { 
     window.removeEventListener('scroll', this.onScroll.bind(this), true); 
    } 
    } 

    onScroll() { 
    const { isLoading, isEndOfSurah } = this.props; 
    console.log('here'); 

    if (isEndOfSurah) { 
     return false; 
    } 

    if (!isLoading && !this.state.lazyLoading && window.pageYOffset > (document.body.scrollHeight - window.innerHeight - 1000)) { 
     // Reached the end. 
     this.setState({ 
     lazyLoading: true 
     }); 

     this.lazyLoadAyahs(); 
    } 
    } 
+0

这是因为它在添加和删除时不是相同的功能。 this.onScroll.bind返回一个新函数。 Javascript是通过引用传递,而函数是对象 - 所以this.onScroll.bind(this)!== this.onScroll.bind(this) –

+0

@gabdallah是有道理的!我有一个感觉是这个问题,但+1 –

回答

2

我会详细说明我的评论。 this.onScroll.bind(this)返回一个新函数,所以每个添加/删除使用的this.onScroll.bind(this)在内存中是一个不同的函数。你可以用===等号运算符来测试它。相反,结合onScroll功能在构造函数中:

constructor(props) { 
    super(props) 
    this.onScroll = this.onScroll.bind(this); 
} 

,然后只用this.onScroll,因为它具有所需的这种结合,将在每一个事件侦听器引用相同的功能。

+0

让我试试吧! –