如何阻止接收Firebase通知的React Hooks组件出现无限重渲染问题
问题根因
你代码中的无限重渲染是useEffect依赖配置错误直接导致的:你将状态notificationList加入了useEffect的依赖数组,同时在useEffect的回调中调用setNotificationList更新该状态。每次状态更新都会触发依赖项变化,进而重新执行useEffect,形成无限执行的死循环。
修复方案
1. 调整useEffect依赖项
如果只需要组件首次挂载时拉取一次缓存的历史通知,直接将useEffect的依赖数组改为空数组,确保它仅在组件挂载时执行一次。同时可以用useCallback包裹跳转方法,避免子组件因为props引用变化产生不必要的重渲染:
import React, { useState, useEffect, useCallback } from 'react'; import NotificationScreen from '../../Components/Notification/Notification'; import { useNavigation } from '@react-navigation/native'; import { getCache } from '../../Services/CachingService'; const Notification = () => { const navigation = useNavigation(); const [notificationList, setNotificationList] = useState([]); // 依赖改为空数组,仅挂载时执行一次 useEffect(() => { getCache('messages').then((messages) => { console.log(`messages`, messages); if (messages) { setNotificationList(messages); } }); }, []); // 用useCallback包裹跳转方法,稳定函数引用 const handleSendNotificationPress = useCallback(() => { navigation.navigate('NotificationMembers'); }, [navigation]); return ( <NotificationScreen NotificationDetails={notificationList} onSendNotificationPress={handleSendNotificationPress} /> ); }; export default Notification;
2. 对接Firebase实时消息更新
如果需要收到新的Firebase推送时自动更新通知列表,不要通过轮询或依赖状态触发拉取,直接监听Firebase的消息接收事件,收到新消息时再用函数式更新修改状态即可,示例逻辑如下:
useEffect(() => { // 原有拉取缓存逻辑 getCache('messages').then((messages) => { if (messages) setNotificationList(messages); }); // 监听Firebase推送新消息事件 const unsubscribe = messaging().onMessage(async remoteMessage => { // 函数式更新可以拿到最新的状态,不需要把notificationList加入依赖 setNotificationList(prevList => { const newList = [...prevList, remoteMessage]; // 这里补充你将新消息存入缓存的逻辑 return newList; }); }); // 组件卸载时取消监听,避免内存泄漏 return unsubscribe; }, []);
内容的提问来源于stack exchange,提问作者AsZik
相关产品推荐
相关产品推荐

