React 客户端使用 Socket.io 接收两个连接

React client receives two connections using Socket.io

我正在使用 SocketIO 开发一个简单的应用程序,但遇到了这个问题。在服务器中我有以下代码:

const httpServer = require('http').createServer();
const socketIO = require('socket.io');
const port = process.env.PORT_WS || 5001;
const io = socketIO(httpServer, { cors: { origin: '*' } });
io.on('connection', (socket) => {
  console.log('Connected to socket');
  socket.on('join-room', () => {
    console.log('joined room')
  });
});

httpServer.listen(port, () => {
  console.log(`Listening on the port ${port}`);
});

在客户端我有以下代码:

import { io } from 'socket.io-client';

export default class SocketConnection {

  constructor() {
    this.initializeSocketConnection();
    this.initializeSocketEvents();
  }

  initializeSocketConnection() {
    console.log('I am here');
    this.socket = io('ws://localhost:5001');
  }

  initializeSocketEvents() {
    this.socket.on('connect', () => {
      console.log('Socket connected');
    });
  }
}

我在控制台中收到两条 Socket connected 消息。

这不是重新呈现问题,因为 I am here 消息仅记录一次。

我在客户端和后端都使用 socket.io 版本 4.0.1

之所以会发生这种情况,是因为在 React 严格模式下,构造函数被调用了两次。 React 似乎隐藏了这一点。由于 console.log('Socket connected'); 在一个“on”事件中,React 没有办法“隐藏”它。因此,'I am here' 将显示一次,而 'Socket connected' 将显示两次。