mirror of
https://github.com/truewhile/MeBox.git
synced 2026-10-02 20:26:36 +08:00
bug处理优化
bug处理优化
This commit is contained in:
@@ -34,6 +34,9 @@ export function useSSE(
|
||||
options: { autoConnect?: boolean } = {}
|
||||
) {
|
||||
const { autoConnect = true } = options
|
||||
const onEventRef = useRef(onEvent)
|
||||
onEventRef.current = onEvent
|
||||
|
||||
const eventSourceRef = useRef<EventSource | null>(null)
|
||||
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const isConnectedRef = useRef(false)
|
||||
@@ -64,7 +67,7 @@ export function useSSE(
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data) as SSEEvent
|
||||
onEvent(data)
|
||||
onEventRef.current(data)
|
||||
} catch (err) {
|
||||
console.error('Failed to parse SSE event:', err)
|
||||
}
|
||||
@@ -84,7 +87,7 @@ export function useSSE(
|
||||
}
|
||||
}
|
||||
|
||||
}, [onEvent])
|
||||
}, [])
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
if (reconnectTimeoutRef.current) {
|
||||
|
||||
@@ -11,6 +11,8 @@ const MAX_RECONNECT_ATTEMPTS = 5
|
||||
export function useWebSocket(onEvent: (topic: string, payload: unknown) => void) {
|
||||
const ref = useRef<WebSocket | null>(null)
|
||||
const token = useAuthStore((s) => s.token)
|
||||
const onEventRef = useRef(onEvent)
|
||||
onEventRef.current = onEvent
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
@@ -32,7 +34,7 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
|
||||
try {
|
||||
const msg = JSON.parse(ev.data)
|
||||
if (msg && typeof msg.topic === 'string') {
|
||||
onEvent(msg.topic, msg.payload)
|
||||
onEventRef.current(msg.topic, msg.payload)
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed frames
|
||||
@@ -52,5 +54,5 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
|
||||
if (timer) window.clearTimeout(timer)
|
||||
ref.current?.close()
|
||||
}
|
||||
}, [token, onEvent])
|
||||
}, [token])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user