websocket useEffect在React without Strict模式下被多次调用

lo8azlld  于 2023-08-05  发布在  React
关注(0)|答案(1)|浏览(98)

我只想运行connect函数一次,以便它启动stompjs客户端。但是它被调用了4次,我在浏览器中收到以下消息:
WebSocket连接到'ws://localhost:3000/chat/251/ios 42 gwd/websocket'失败:WebSocket在建立连接之前关闭。
第四次连接到WebSocket。
如果我理解正确的话,useRef应该在两次重新呈现之间保持值,但显然它没有这样做,因为我得到了clientInit.current=false四次。
我做错了什么?

function App() {
  const [userData, setUserData] = useState({
    userId: null,
    name: "",
    connected: false,
  });

  const [connected, setConnected] = useState(false);
  const [stompClient, setStompClient] = useState(null);

  const clientInit = useRef(false);

  //should be called only once? but called 4 times. getting clientInit.current= false 4 times 
 too 
  const connect = () => {         console.log("inside connect");
    console.log("====================================");
    console.log(clientInit.current);
    console.log("====================================");
    clientInit.current = true;

    const socket = new SockJS("/chat");
    const tempstompClient = Stomp.over(socket);
    tempstompClient.connect(
      { "client-id": userData.userId },
      () => {
        setConnected(true);
        setStompClient(tempstompClient);
      },
      (er) => {
        console.error(er);
      }
    );
  };

  const registerUser = (e) => {
    e.preventDefault();
    setUserData({ ...userData, connected: true });
  };

  const handleUser = (event) => {
    const { value } = event.target;
    const uuid = uuidv4();
    setUserData({ ...userData, name: value, userId: uuid });
  };
  useEffect(() => {
    console.log("====================================");
    console.log("calling connect:", clientInit.current);
    console.log("====================================");
    if(!clientInit)
      connect();

    return () => {
      console.log("Doing stuff inside cleaning up", stompClient);
      if (stompClient) {
        console.log("====================================");
        console.log("disconnecting", stompClient);
        console.log("====================================");
        stompClient.disconnect();
      }
    };
  }, []);

  return userData.connected ? (
    <Chatbox
      userData={userData}
      stompClient={stompClient}
      connected={connected}
    />
  ) : (
    <Register handleUser={handleUser} handleSubmit={registerUser} />
  );
}

export default App;

字符串

x6yk4ghg

x6yk4ghg1#

当我尝试使用vite而不是react-scripts时,问题就消失了。我猜,由于某种原因,react-scripts正在安装,不必要地多次卸载组件

相关问题