[React-Native-Firebase]如何删除onMessage存在的事件?

时间:2017-12-22 03:08:08

标签: react-native react-native-firebase

我声明了一个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

}

1 个答案:

答案 0 :(得分:1)

如果你检查docs 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
}