代码之家  ›  专栏  ›  技术社区  ›  James Delaney

这是如何取消react活动的订阅?

  •  1
  • James Delaney  · 技术社区  · 6 年前

    我不确定我这样做是否正确?

    async componentDidMount() {
      const claimNumber = 'T1339838'
      const {
        runtime
      } = this.context
      const data = await runtime.select('comments-get', {
        claimNumber: claimNumber
      })
      this.setState({
        commentsData: data
      })
    
      const commentsUpdated = runtime.fb.ref('/comments')
      commentsUpdated.on('value', childSnapshot => {
        this.updateComments(childSnapshot.val())
      })
    }
    
    componentWillUnmount() {
      // TODO: Remove on listener
      window.removeEventListener('resize', this.commentsUpdated)
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Manoj Kumar    6 年前

    只有将事件侦听器添加到window对象时,才应使用window.removeEventListener。例如,如果要使用以下代码添加事件侦听器:

    //添加侦听器

    window.addEventListener('resize', this.commentsUpdated);
    

    componentWillUnmount() {
        // TODO: Remove on listener
        window.removeEventListener('resize', this.commentsUpdated)
    }
    

    在上述情况下,只需清空或将null赋给this.commentsUpdated即可。