Novu新通知触发Mantine弹窗异常:refetch后notifications为空
问题原因及解决方案
核心原因
- React的状态更新是异步的,调用
refetch()触发数据重新获取后,当前函数闭包中的notifications还是旧的状态值,不会立刻更新为新数据,所以打印出来仍是空数组。 useNotifications的refetch方法仅负责触发重新请求,不会直接同步返回最新数据,你需要等待组件状态更新后才能拿到新的notifications。
解决办法
办法一:直接使用refetch的返回值
如果你的useNotifications钩子的refetch方法会返回最新的通知数据(类似React Query的refetch返回带data的对象),可以直接用返回值处理:
const handleNewNotification = async () => { const response = await refetch(); // 假设response.data为最新通知列表,根据实际返回结构调整 const newNotifications = response.data; console.log(newNotifications); newNotifications.forEach((n) => { showNotification({ id: n._id, title: 'New Notification', message: `${n.content}`, autoClose: false, onClose: ({ id }) => { markAsSeen(id); } }) }) }
办法二:监听notifications状态变化
通过useEffect监听notifications的变化,当状态更新后再触发弹窗逻辑:
// 提取弹窗逻辑为单独函数 const showNewNotifications = (notificationsList) => { notificationsList.forEach((n) => { showNotification({ id: n._id, title: 'New Notification', message: `${n.content}`, autoClose: false, onClose: ({ id }) => { markAsSeen(id); } }) }) } // 仅负责触发重新获取数据 const handleNewNotification = async () => { await refetch(); } // 监听notifications变化,有新数据时弹窗 useEffect(() => { if (notifications.length > 0) { showNewNotifications(notifications); } }, [notifications])
办法三:利用Socket事件返回的数据直接处理
如果unseen_count_changed事件返回的data包含新增通知的信息,可以直接用这些数据弹窗,避免重复请求:
useEffect(() => { if (novuSocket) { novuSocket.on('unseen_count_changed', async (data) => { console.log(data); // 假设data.newNotifications是新增的通知列表,根据实际结构调整 if (data.newNotifications?.length > 0) { data.newNotifications.forEach((n) => { showNotification({ id: n._id, title: 'New Notification', message: `${n.content}`, autoClose: false, onClose: ({ id }) => { markAsSeen(id); } }) }) } else { await refetch(); } }); } return () => { if (novuSocket) { novuSocket.off('unseen_count_changed'); } } }, [novuSocket])
内容的提问来源于stack exchange,提问作者The Code Crusader
相关产品推荐
相关产品推荐

