我已经卸载了绑定(bind)到窗口事件监听器的函数。仍然,在转到下一页后,事件中的函数虽然被删除了,但仍然执行?这可能是什么问题?
componentDidMount(){
window.addEventListener("resize", this.updateDimensions.bind(this));
}
componentWillUnmount(){
console.log("unmounting....");
window.removeEventListener('resize', this.updateDimensions.bind(this));
}
这是绑定(bind)附加到事件的函数:
updateDimensions(){
if (this.refs.get_it.clientWidth < 774){
this.setState({
width:this.refs.get_it.clientWidth,
height:400,
flag:true});
}
}
最佳答案
你的代码有点困惑
componentDidMount(){
window.addEventListener("resize", this.updateDimensions.bind(this));
// first instance listening to event
}
componentWillUnmount(){
console.log("unmounting....");
window.removeEventListener('resize', this.updateDimensions.bind(this));
// second instance removed from listener here first!== second
}
试试这个
constructor(props) {
super(props);
this.updateDimensions = this.updateDimensions.bind(this);
}
componentDidMount(){
window.addEventListener("resize", this.updateDimensions);
// first instance listening to event
}
componentWillUnmount(){
console.log("unmounting....");
window.removeEventListener('resize', this.updateDimensions);
// same instance removed from listener here first == second
}
关于javascript - 函数已卸载但仍在事件监听器上执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133311/