解决messaging().onNotificationOpenedApp点击通知多次调用问题
解决messaging().onNotificationOpenedApp多次调用的问题
核心原因
每次组件挂载(比如React严格模式下的双重渲染、组件重新挂载)时,你的useEffect都会重复注册onNotificationOpenedApp的回调,导致同一个通知触发时多个回调被执行。
解决方案1:添加清理函数移除监听
Firebase Messaging的onNotificationOpenedApp会返回一个取消监听的函数,在组件卸载时执行该函数,就能避免重复注册回调:
useEffect(() => { // 保存监听的取消函数 const unsubscribe = messaging().onNotificationOpenedApp(async remoteMessage => { if (remoteMessage) { const notification = JSON.parse(String(remoteMessage.data)); const notificationData = NotificationMapper([notification]); await notificationNavigation(notificationData[0]); } }); // 组件卸载时取消监听 return () => unsubscribe(); }, []);
解决方案2:用Ref标记已处理的通知
如果清理函数仍无法避免重复执行(比如通知数据重复触发),可以添加一个Ref记录已处理的通知ID,跳过重复逻辑:
import { useRef } from 'react'; // ... const processedNotifications = useRef(new Set()); useEffect(() => { const unsubscribe = messaging().onNotificationOpenedApp(async remoteMessage => { if (remoteMessage) { const notification = JSON.parse(String(remoteMessage.data)); // 假设你的通知有唯一标识字段,比如notification.id if (processedNotifications.current.has(notification.id)) return; processedNotifications.current.add(notification.id); const notificationData = NotificationMapper([notification]); await notificationNavigation(notificationData[0]); } }); return () => unsubscribe(); }, []);
额外提示:React严格模式的影响
开发环境下React严格模式会让useEffect执行两次,这也会导致监听被注册两次。上述清理函数的方式可以解决这个问题——第一次注册的监听会在第二次执行前被清理。
内容的提问来源于stack exchange,提问作者MURARI Yadav
相关产品推荐
相关产品推荐

