【问题标题】:messages not getting added when using socket.io使用 socket.io 时未添加消息
【发布时间】:2021-11-15 13:58:47
【问题描述】:

我正在尝试设计一个在反应中使用套接字的聊天应用程序。每当从后端触发new_message 事件时,我都会尝试将该消息附加到现有消息数组中,但似乎这不起作用。 这是我尝试过的代码:

useEffect(() => {
    socket.on("new_message", (data) => {                 // receving the event and appending the new message in the existing array of messages. 
      setConversation([...conversation, data.message]);
    });
  });

  useEffect(() => {
    socket.emit("join_room", lead._id);
    if (lead._id !== undefined) {
      getConversationByRoomId(lead._id).then(({ data }) =>
        setConversation(data.conversation)
      );
    }
  }, [lead]);

  const handleKeyPress = async (e) => {
    if (e.key === "Enter") {
      await postMessage(lead._id, { messageText: message });     // API which will save this message in the database and triggers an event called new_message to the socket
      setMessage("");
    }
  };

不知何故,它只是在对话数组中添加了新消息,并删除了所有其他对话。有什么办法可以解决这个问题?

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

    根据您在问题中提供的信息,我认为首先要更改和观察的是socket.on 的实施方式。每次状态更新发生时,我都不会绑定新的事件处理程序,并且也不会在清理函数中删除前一个事件处理程序。

    利用状态更新器功能尝试以下方式:-

    useEffect(() => {
        socket.on("new_message", (data) => {                
          setConversation(prevConversation=>[...prevConversation, data.message]);
        });
      },[]);
    

    还要确保 getConversationByRoomId 实际上返回整个 conversation 数组,方法是在状态设置之前记录它的值。

    【讨论】:

      猜你喜欢
      • 2019-10-09
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2013-11-12
      相关资源
      最近更新 更多