使用静态方法删除 componentWillUnmount 上的侦听器

约翰尼·Q

我正在使用静态方法来实现我的侦听器功能。例子:

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)
  }
}

侦听器添加得很好,但是,在卸载组件时,该函数似乎没有被删除,并且仍然触发我的静态方法。我认为this.constructor.listenerFunc === this.constructor.listenerFunc因为它是一个类方法,但在我的示例中似乎并非如此。我错过了什么?

更新

我更新了我的代码。我的侦听器函数实际上调用了另一个static方法heavyCalculation这就是把事情搞砸的地方。

约翰尼·Q

我不确定是我的 babel 转译器还是 React 本身,但我使用类名解决了它。这是我更新的代码:

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)
  }
}

因此,this.heavyCalculation()没有调用,而是使用MyComponent.heavyCalculation(). 解决它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章