.bind
总是会创建一个新函数,因此您需要执行以下操作,因此它会添加和删除相同的函数。
constructor(props){
super(props);
this.onScroll = this.onScroll.bind(this); //bind function once
}
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
// you need to unbind the same listener that was binded.
window.removeEventListener('scroll', this.onScroll, false);
}