简体   繁体   中英

Firebase Cloud Messaging Notification - message is received multiply times

I'm trying to catch a notification in the foreground with react native, using react-native-firebase.

If the app is in the background, the notification is being shown only once as it should (obviously because it's not handled within the app). But when the app is in the foreground, the callback function to catch the notification is triggered multiple times, in a quite random fashion. If I refresh the app and then send again usually the number grows exponentially, and can reach 12 times or more.

My very simple code:

import React, { Component } from 'react';
import {
  View,
  Text,
} from 'react-native';


import messaging from '@react-native-firebase/messaging';


class App extends Component {

  async componentDidMount() {
    messaging().onMessage(async message => console.log("message received!!!")
  }


  render(){
    return (
      <View>
        <Text>Notification App</Text>
      </View>
    )
  }
}

export default App;

To send the notification, I'm using Firebase cloud messaging test system:

在此处输入图像描述

I know my FCM token id so it's easy. My question is how can I make the call back function messaging().onMessage trigger only once

if you don't remove the messaging listener when the app component is unmounted, then your app can have multiple listeners and then receive message multiple times. try to edit your code like this to delete listener when component unmount:

async componentDidMount() {
    this.messageListener = messaging().onMessage(async message => console.log("message received!!!")
  }

componentWillUnmount() {
    this.messageListener();
}

I found out that the problem was the hot reload, apperantly in you refresh the app using hot reload it doesn't remove the listener, so you need to refresh from the device manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM