我在我的一个组件中监听窗口“滚动”事件。然而,当组件被卸载时,滚动事件监听器并没有被移除。
卸载组件后发生滚动事件时会产生以下错误:
warning.js:36 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the TopNavDesktop component.
如何正确删除此事件监听器?
示例代码:
class NavBar extends Component {
constructor() {
super();
this.state = {
distanceScrolled: null
}
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll.bind(this));
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll.bind(this));
}
handleScroll(e){
const distanceScrolled = e.srcElement.body.scrollTop;
this.setState({ distanceScrolled: distanceScrolled });
}
render { ... }
}
最佳答案
当您删除监听器时,您正在创建一个新的函数引用。
someFn.bind(this) === someFn.bind(this)
将计算为 false。
相反,将函数保存在构造函数中并使用该引用:
class NavBar extends Component {
constructor() {
super();
this.state = {
distanceScrolled: null
}
this.scrollFn = this.handleScroll.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.scrollFn);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollFn);
}
handleScroll(e){
const distanceScrolled = e.srcElement.body.scrollTop;
this.setState({ distanceScrolled: distanceScrolled });
}
render { ... }
}
关于javascript - 在 React 组件卸载时删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165169/