小编Sus*_*van的帖子

使用 React Hooks 重新连接 Web 套接字

我想与服务器建立网络套接字连接。如果连接关闭,则在 5 秒后重新连接。我正在使用 React Hooks,到目前为止实现了这一目标

import React, { useRef, useState, useEffect } from 'react';`
import './App.css';
function App() {
 const wsClient = useRef(null);
 const [wsState, setWsState] = useState(true)
 useEffect(() => {
    wsClient.current = new WebSocket(url);
    console.log("Trying to open ws");
    setWsState(true)
    
    wsClient.current.onopen = () => {
      console.log('ws opened');
      wsClient.current.send('{"type" : "hello"}')
    };
    wsClient.current.onclose = (event) => {
      // Parse event code and log
      setTimeout(() => {setWsState(false)}, 5000)
      console.log('ws closed');
    }
    wsClient.current.onmessage = ((event) => {
      // DO YOUR JOB
    })
    return …
Run Code Online (Sandbox Code Playgroud)

websocket reactjs react-hooks

2
推荐指数
1
解决办法
2076
查看次数

标签 统计

react-hooks ×1

reactjs ×1

websocket ×1