From 73d9ff75088efb6b54082c40fedcf1a51c3b1c45 Mon Sep 17 00:00:00 2001 From: dongmucat <1127093059@qq.com> Date: Tue, 10 Dec 2024 13:54:42 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DreadyState=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/hooks/src/useWebSocket/index.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/hooks/src/useWebSocket/index.ts b/packages/hooks/src/useWebSocket/index.ts index 8260195133..a8c1329ff7 100644 --- a/packages/hooks/src/useWebSocket/index.ts +++ b/packages/hooks/src/useWebSocket/index.ts @@ -43,18 +43,19 @@ export default function useWebSocket(socketUrl: string, options: Options = {}): protocols, } = options; + const [latestMessage, setLatestMessage] = useState(); + const [readyState, setReadyState] = useState(ReadyState.Closed); + const onOpenRef = useLatest(onOpen); const onCloseRef = useLatest(onClose); const onMessageRef = useLatest(onMessage); const onErrorRef = useLatest(onError); + const readyStateRef = useLatest(readyState); const reconnectTimesRef = useRef(0); const reconnectTimerRef = useRef>(); const websocketRef = useRef(); - const [latestMessage, setLatestMessage] = useState(); - const [readyState, setReadyState] = useState(ReadyState.Closed); - const reconnect = () => { if ( reconnectTimesRef.current < reconnectLimit && @@ -123,7 +124,7 @@ export default function useWebSocket(socketUrl: string, options: Options = {}): }; const sendMessage: WebSocket['send'] = (message) => { - if (readyState === ReadyState.Open) { + if (readyStateRef.current === ReadyState.Open) { websocketRef.current?.send(message); } else { throw new Error('WebSocket disconnected');