reactjs removeListener不使用es6类
删除窗口上的事件侦听器不起作用,就像添加和删除事件侦听器时它不是同一个函数一样。如何解决这个问题?我还试图将reactjs removeListener不使用es6类,reactjs,Reactjs,删除窗口上的事件侦听器不起作用,就像添加和删除事件侦听器时它不是同一个函数一样。如何解决这个问题?我还试图将onScroll方法抽象到类之外以及文件中的更高级别,但也没有成功 componentDidMount() { if (__CLIENT__) { window.removeEventListener('scroll', this.onScroll.bind(this), true); console.log('mounting') window
onScroll
方法抽象到类之外以及文件中的更高级别,但也没有成功
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();
}
}
我将详细阐述我的评论。this.onScroll.bind(this)返回一个新函数,因此用于每个添加/删除的每个this.onScroll.bind(this)在内存中都是一个不同的函数。您可以使用===相等运算符来测试这一点。而是在构造函数中绑定onScroll函数:
constructor(props) {
super(props)
this.onScroll = this.onScroll.bind(this);
}
然后只需使用this.onScroll,因为它将具有所需的this绑定,并且将是每个事件侦听器中引用的相同函数。这是因为添加和删除时它不是相同的函数。this.onScroll.bind返回一个新函数。Javascript是按引用传递的,函数是对象-因此this.onScroll.bind(this)!=这个.onScroll.bind(这个)@gabdalah有道理!我觉得这就是问题所在,但让我试试看!