[英]Remove listener on componentWillUnmount using static methods
I'm using static methods to implement my listener functions. 我正在使用静态方法来实现我的侦听器函数。 Example:
例:
class MyComponent extends Component {
static heavyCalculation() { console.log('Calculating') }
static listenerFunc() { console.log('Resize'); this.heavyCalculation() }
componentDidMount() {
window.addEventListener('resize', this.constructor.listenerFunc, false)
}
componentWillUnmount() {
window.removeEventListener('resize', this.constructor.listenerFunc, false)
}
}
The listener adds fine, however, when unmounting the component, the function doesn't seem to get removed, and still triggering my static method. 监听器添加正常,但是,在卸载组件时,该函数似乎没有被删除,仍然触发我的静态方法。 I thought
this.constructor.listenerFunc === this.constructor.listenerFunc
since it's a class method, but in my example it doesn't seem so. 我认为
this.constructor.listenerFunc === this.constructor.listenerFunc
因为它是一个类方法,但在我的例子中它似乎并非如此。 What am I missing? 我错过了什么?
I updated my code. 我更新了我的代码。 My listener function actually calls another
static
method heavyCalculation
. 我的监听器函数实际上调用另一个
static
方法heavyCalculation
。 This is where it mess things up. 这是搞乱的地方。
The third argument is mandatory. 第三个参数是强制性的。
See: removeEventListener is not working 请参阅: removeEventListener不起作用
Also, make sure that you've bound this
to your function. 此外,请确保您已
this
绑定到您的功能。
componentDidMount() {
window.addEventListener('resize', this.constructor.listenerFunc, false)
}
componentWillUnmount() {
window.removeEventListener('resize', this.constructor.listenerFunc, false)
}
this.constructor.listenerFunc = this.constructor.listenerFunc.bind(this)
See: I can't seem to reliably remove a listener using componentWillUnmount 请参阅: 我似乎无法使用componentWillUnmount可靠地删除侦听器
I'm not sure whether it's my babel transpiler or React itself but I solved it using the classname. 我不确定它是我的babel转换器还是React本身但是我使用classname解决了它。 Here's my updated code:
这是我更新的代码:
class MyComponent extends Component {
static heavyCalculation() { console.log('Calculating') }
static listenerFunc() {
console.log('Resize')
MyComponent.heavyCalculation()
}
componentDidMount() {
window.addEventListener('resize', this.constructor.listenerFunc, false)
}
componentWillUnmount() {
window.removeEventListener('resize', this.constructor.listenerFunc, false)
}
}
So instead of calling this.heavyCalculation()
I used MyComponent.heavyCalculation()
. 所以我没有调用
this.heavyCalculation()
而是使用了MyComponent.heavyCalculation()
。 Solves it. 解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.