Javascript 已卸载但仍在eventlistener上执行的函数
我已经卸载了绑定到窗口事件侦听器的函数。尽管如此,在进入下一页后,事件中的函数仍然会执行,尽管被删除了?这里可能有什么问题Javascript 已卸载但仍在eventlistener上执行的函数,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我已经卸载了绑定到窗口事件侦听器的函数。尽管如此,在进入下一页后,事件中的函数仍然会执行,尽管被删除了?这里可能有什么问题 componentDidMount(){ window.addEventListener("resize", this.updateDimensions.bind(this)); } componentWillUnmount(){ console.log("unmounting...."); window.removeEven
componentDidMount(){
window.addEventListener("resize", this.updateDimensions.bind(this));
}
componentWillUnmount(){
console.log("unmounting....");
window.removeEventListener('resize', this.updateDimensions.bind(this));
}
以下是绑定到事件的函数:
updateDimensions(){
if (this.refs.get_it.clientWidth < 774){
this.setState({
width:this.refs.get_it.clientWidth,
height:400,
flag:true});
}
}
updateDimensions(){
if(this.refs.get_it.clientWidth<774){
这是我的国家({
宽度:this.refs.get_it.clientWidth,
身高: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
}
你的代码有点混乱
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
}
只是想写同样的--Tnx很多,节省了我的时间,从现在起总是将我的方法绑定在构造函数中,糟糕的做法..很高兴帮助你。您是否也可以接受答案:)或将方法定义为绑定类方法:
updateDimensions=(…args)=>{/*code*/}
只是想编写相同的-ux很多,节省了我的时间,从现在起总是在构造函数中绑定我的方法,糟糕的做法..很高兴帮助您。您是否也可以接受答案:)或将方法定义为绑定类方法:updateDimensions=(…args)=>{/*code*/}