Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 用钩关闭时重新打开腹板箱_Reactjs_Websocket_React Hooks - Fatal编程技术网

Reactjs 用钩关闭时重新打开腹板箱

Reactjs 用钩关闭时重新打开腹板箱,reactjs,websocket,react-hooks,Reactjs,Websocket,React Hooks,我正在React应用程序中使用WebSocket。 任务之一是在连接关闭时重新打开连接 不知道怎么做。看起来很有效,但我不知道这是否足够: export const useWebSocket = () => { const webSocket = useRef(); useEffect(() => { webSocket.current = new WebSocket("ws://url"); webSocket

我正在React应用程序中使用WebSocket。 任务之一是在连接关闭时重新打开连接

不知道怎么做。看起来很有效,但我不知道这是否足够:

export const useWebSocket = () => {
    const webSocket = useRef();

    useEffect(() => {
        webSocket.current = new WebSocket("ws://url");

        webSocket.current.onclose = event => {
            if (!event.wasClean) {
                webSocket.current = new WebSocket("ws://url");
            }
        }

        return () => webSocket.current.close();
    }, []);
}

我上面的解决方案中存在一个问题:重新连接后,消息无法到达
webSocket.current.onmessage