连接 Websocket 事件以更新我的 React 组件的正确方法

Correct way of connecting Websocket events to update my React Component

所以我主要是一名 C++ 后端开发人员,但我也在学习 React,并且我有这个非常简单的文件来使用 websockets。

import React, { useState } from "react";

var serverMessage = "";
var webSocketReady = false;

function connect() {
   webSocket = new WebSocket("ws://127.0.0.1:3000/ws")

   webSocket.onopen = (event) => {
     webSocketReady = true;
   };

   webSocket.onmessage = function (event) {
     serverMessage = JSON.parse(event.data);
   };

   webSocket.onclose = function (event)
   {
     webSocketReady = false;
     setTimeout(function() {
         connect();
       }, 1000);
   };

   webSocket.onerror = function (err)
   {
     console.log('Socket encountered error: ', err.message, 'Closing socket')
     webSocket.close();
   };
}

connect();

export default function MyTestComponent({
  ...props
}) {
   const [varThatNeedHooks, setVar] = useState({});
   if (!webSocketReady)
   {
     return (<h1>Could not connect to server retrying ...</h1>);
   }
   else if (serverMessage == "")
   {
     return (<h1>Waiting for message from server ...</h1>);
   }
   else
   {
     // do stuff with varThatNeedHooks
   }
}

我正在查看 React 文档,我意识到我将 websocket 连接到 MyTestComponent 的方式一定是错误的。但我不确定从 websocket 连接事件以更改呈现内容的“React”方式是什么。任何人都有我可以遵循的任何好的文档或示例吗?

通常,您会将 serverMessagewebSocketReady 设为 React 状态的一部分,以便在更新它们时触发组件重新渲染。使用 useEffect 挂钩来管理套接字实例。

示例:

import React, { useEffect, useState, useRef } from "react";

export default function MyTestComponent({ ...props }) {
  const [varThatNeedHooks, setVar] = useState({});
  const [serverMessage, setServerMessage] = useState("");
  const [webSocketReady, setWebSocketReady] = useState(false);

  const [webSocket, setWebSocket] = useState(new WebSocket("ws://127.0.0.1:3000/ws"));

  useEffect(() => {
    webSocket.onopen = (event) => {
      setWebSocketReady(true);
    };

    webSocket.onmessage = function (event) {
      setServerMessage(JSON.parse(event.data));
    };

    webSocket.onclose = function (event) {
      setWebSocketReady(false);
      setTimeout(() => {
        setWebSocket(new WebSocket("ws://127.0.0.1:3000/ws"));
      }, 1000);
    };

    webSocket.onerror = function (err) {
      console.log('Socket encountered error: ', err.message, 'Closing socket');
      setWebSocketReady(false);
      webSocket.close();
    };

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

  if (!webSocketReady) {
    return <h1>Could not connect to server retrying ...</h1>;
  } else if (serverMessage == "") {
    return <h1>Waiting for message from server ...</h1>;
  } else {
    // do stuff with varThatNeedHooks
  }
}