Files
vf_react/src/hooks/useEventNotifications.js
zdl a9dc1191bf feat:. mockSocketService 添加 connecting 状态
- 新增 connecting 标志防止重复连接
  - 在 connect() 方法中检查 connected 和 connecting 状态
  - 连接成功或失败后清除 connecting 标志\
2. NotificationContext 调整监听器注册顺序

  - 在 useEffect 中重新排序初始化步骤
  - 第一步:注册所有事件监听器(connect, disconnect, new_event 等)
  - 第二步:获取最大重连次数
  - 第三步:调用 socket.connect()
  - 使用空依赖数组 [] 防止 React 严格模式重复执行\
3. logger 添加日志限流

  - 实现 shouldLog() 函数,1秒内相同日志只输出一次
  - 使用 Map 缓存最近日志,带最大缓存限制(100条)
  - 应用到所有 logger 方法:info, warn, debug, api.request, api.response
  - 错误日志(error, api.error)不做限流,始终输出\
修复 emit 时机确保事件被接收

  - 在 mockSocketService 的 connect() 方法中
  - 使用 setTimeout(0) 延迟 emit(connect) 调用
  - 确保监听器注册完毕后再触发事件\
2025-10-27 13:13:56 +08:00

229 lines
8.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/hooks/useEventNotifications.js
/**
* React Hook用于在组件中订阅事件推送通知
*
* 使用示例:
* ```jsx
* import { useEventNotifications } from 'hooks/useEventNotifications';
*
* function MyComponent() {
* const { newEvent, isConnected } = useEventNotifications({
* eventType: 'all',
* importance: 'all',
* onNewEvent: (event) => {
* console.log('收到新事件:', event);
* // 显示通知...
* }
* });
*
* return <div>...</div>;
* }
* ```
*/
import { useEffect, useState, useRef } from 'react';
import socket from '../services/socket';
import { logger } from '../utils/logger';
export const useEventNotifications = (options = {}) => {
const {
eventType = 'all',
importance = 'all',
enabled = true,
onNewEvent,
} = options;
const [isConnected, setIsConnected] = useState(false);
const [newEvent, setNewEvent] = useState(null);
const [error, setError] = useState(null);
const unsubscribeRef = useRef(null);
// 使用 ref 存储 onNewEvent 回调,避免因回调函数引用改变导致重新连接
const onNewEventRef = useRef(onNewEvent);
// 每次 onNewEvent 改变时更新 ref
useEffect(() => {
onNewEventRef.current = onNewEvent;
}, [onNewEvent]);
useEffect(() => {
console.log('[useEventNotifications DEBUG] ========== useEffect 执行 ==========');
console.log('[useEventNotifications DEBUG] enabled:', enabled);
console.log('[useEventNotifications DEBUG] eventType:', eventType);
console.log('[useEventNotifications DEBUG] importance:', importance);
// 如果禁用,则不订阅
if (!enabled) {
console.log('[useEventNotifications DEBUG] ⚠️ 订阅已禁用,跳过');
return;
}
// 连接状态监听
const handleConnect = () => {
console.log('[useEventNotifications DEBUG] ✓ WebSocket 已连接');
logger.info('useEventNotifications', 'WebSocket connected');
setIsConnected(true);
setError(null);
};
const handleDisconnect = () => {
console.log('[useEventNotifications DEBUG] ⚠️ WebSocket 已断开');
logger.warn('useEventNotifications', 'WebSocket disconnected');
setIsConnected(false);
};
const handleConnectError = (err) => {
console.error('[useEventNotifications ERROR] WebSocket 连接错误:', err);
logger.error('useEventNotifications', 'WebSocket connect error', err);
setError(err);
setIsConnected(false);
};
// 监听连接事件必须在connect之前设置否则可能错过事件
socket.on('connect', handleConnect);
socket.on('disconnect', handleDisconnect);
socket.on('connect_error', handleConnectError);
// 连接 WebSocket
console.log('[useEventNotifications DEBUG] 准备连接 WebSocket...');
logger.info('useEventNotifications', 'Initializing WebSocket connection');
// 先检查是否已经连接
const alreadyConnected = socket.connected || false;
console.log('[useEventNotifications DEBUG] 当前连接状态:', alreadyConnected);
logger.info('useEventNotifications', 'Pre-connection check', { isConnected: alreadyConnected });
if (alreadyConnected) {
// 如果已经连接,直接更新状态
console.log('[useEventNotifications DEBUG] Socket已连接直接更新状态');
setIsConnected(true);
} else {
// 否则建立新连接
socket.connect();
}
// 新事件处理函数 - 使用 ref 中的回调
const handleNewEvent = (eventData) => {
console.log('\n[useEventNotifications DEBUG] ========== Hook 收到新事件 ==========');
console.log('[useEventNotifications DEBUG] 事件数据:', eventData);
console.log('[useEventNotifications DEBUG] 事件 ID:', eventData?.id);
console.log('[useEventNotifications DEBUG] 事件标题:', eventData?.title);
console.log('[useEventNotifications DEBUG] 设置 newEvent 状态');
setNewEvent(eventData);
console.log('[useEventNotifications DEBUG] ✓ newEvent 状态已更新');
// 调用外部回调(从 ref 中获取最新的回调)
if (onNewEventRef.current) {
console.log('[useEventNotifications DEBUG] 准备调用外部 onNewEvent 回调');
onNewEventRef.current(eventData);
console.log('[useEventNotifications DEBUG] ✓ 外部 onNewEvent 回调已调用');
} else {
console.log('[useEventNotifications DEBUG] ⚠️ 没有外部 onNewEvent 回调');
}
console.log('[useEventNotifications DEBUG] ========== Hook 事件处理完成 ==========\n');
};
// 订阅事件推送
console.log('\n[useEventNotifications DEBUG] ========== 开始订阅事件 ==========');
console.log('[useEventNotifications DEBUG] eventType:', eventType);
console.log('[useEventNotifications DEBUG] importance:', importance);
console.log('[useEventNotifications DEBUG] enabled:', enabled);
// 检查 socket 是否有 subscribeToEvents 方法mockSocketService 和 socketService 都有)
if (socket.subscribeToEvents) {
socket.subscribeToEvents({
eventType,
importance,
onNewEvent: handleNewEvent,
onSubscribed: (data) => {
console.log('\n[useEventNotifications DEBUG] ========== 订阅成功回调 ==========');
console.log('[useEventNotifications DEBUG] 订阅数据:', data);
console.log('[useEventNotifications DEBUG] ========== 订阅成功处理完成 ==========\n');
},
});
console.log('[useEventNotifications DEBUG] ========== 订阅请求已发送 ==========\n');
} else {
console.warn('[useEventNotifications] socket.subscribeToEvents 方法不存在');
}
// 保存取消订阅函数
unsubscribeRef.current = () => {
if (socket.unsubscribeFromEvents) {
socket.unsubscribeFromEvents({ eventType });
}
};
// 组件卸载时清理
return () => {
console.log('\n[useEventNotifications DEBUG] ========== 清理 WebSocket 订阅 ==========');
// 取消订阅
if (unsubscribeRef.current) {
console.log('[useEventNotifications DEBUG] 取消订阅...');
unsubscribeRef.current();
}
// 移除监听器
console.log('[useEventNotifications DEBUG] 移除事件监听器...');
socket.off('connect', handleConnect);
socket.off('disconnect', handleDisconnect);
socket.off('connect_error', handleConnectError);
// 注意:不断开连接,因为 socket 是全局共享的
// 由 NotificationContext 统一管理连接生命周期
console.log('[useEventNotifications DEBUG] ========== 清理完成 ==========\n');
};
}, [eventType, importance, enabled]); // 移除 onNewEvent 依赖
return {
newEvent, // 最新收到的事件
isConnected, // WebSocket 连接状态
error, // 错误信息
clearNewEvent: () => setNewEvent(null), // 清除新事件状态
};
};
/**
* 简化版 Hook只订阅所有事件
*/
export const useAllEventNotifications = (onNewEvent) => {
return useEventNotifications({
eventType: 'all',
importance: 'all',
onNewEvent,
});
};
/**
* Hook订阅重要事件S 和 A 级)
*/
export const useImportantEventNotifications = (onNewEvent) => {
const [importantEvents, setImportantEvents] = useState([]);
const handleEvent = (event) => {
// 只处理 S 和 A 级事件
if (event.importance === 'S' || event.importance === 'A') {
setImportantEvents(prev => [event, ...prev].slice(0, 10)); // 最多保留 10 个
if (onNewEvent) {
onNewEvent(event);
}
}
};
const result = useEventNotifications({
eventType: 'all',
importance: 'all',
onNewEvent: handleEvent,
});
return {
...result,
importantEvents,
clearImportantEvents: () => setImportantEvents([]),
};
};
export default useEventNotifications;