Socket.io 不向客户端发送数组的当前状态

Socket.io not emitting the current state of an array to client side

我正在尝试在 React 应用程序中使用 socket.io 和 node.js(& 表达)向客户端发送对象数组。当您 console.log 服务器端的数组时,它显示更新后的数组,但是当您将相同的数组发送到客户端时,它显示数组的先前状态。

服务器端:


    let onlineUsers = [];

    const addNewUser = (username, socketId) => {
    !onlineUsers.includes((user) => user.username) &&
    onlineUsers.push({ username, socketId });
    };

    io.on('connection', socket => {

    socket.on("newUser", (username) => {
      addNewUser(username, socket.id);
        console.log(onlineUsers)
      });
    
      socket.emit("allUsers", onlineUsers);```

    Client side: 

    ```     socket.current.emit('newUser', user);
        socket.current.on("allUsers", onlineUsers => {
        // setAllusers(users);
        console.log(onlineUsers);
        })```

     The onlineUsers array here records username of each user on login. Why is it not emitting the current state of the array to client side? Thanks in advance if anyone could help. Please comment if need more info. 

问题出在您在 addNewUser() 函数添加数据之前发送数据的服务器上,因此它会发送旧值。

将数据添加到数组后,在套接字消息侦听器中发送数据。

例子

socket.on("newUser", (username) => {
  addNewUser(username, socket.id);
  console.log(onlineUsers)
  socket.emit("allUsers", onlineUsers);
});