3

我声明了一个 onMessage 函数来做一些事情。但是当我导航到另一个屏幕并想要删除 ComponentWillUnmount() 中的 FCM.onMessage() 时。我怎样才能删除它?

const rnfirebase = RNFirebase.initializeApp()

export const FCM = rnfirebase.messaging()

ComponentDidMount(){
    FCM.onMessage((notif)=>{

        //Do something

    })

}
ComponentWillUnmount(){
    //I want to remove here

}
4

1 回答 1

8

如果您检查文档onMessage 返回一个函数,如果控制台记录该函数,您将看到类似这样的内容

ƒ () {
    return rnListener.remove();
  }

因此,当您调用 onMessage 返回的函数时,它将停止侦听,在您的情况下,代码将如下所示

const rnfirebase = RNFirebase.initializeApp()

export const FCM = rnfirebase.messaging()

componentDidMount(){
    this.notificationListener = FCM.onMessage(notif=>{
        //Do something
    })
}

componentWillUnmount(){
    this.notificationListener(); //This will remove the listener
}
于 2018-01-09T18:58:09.807 回答