如何让消息立即显示?它适用于新对话(第一块),但不适用于现有对话(第二块)

How do I get messages to appear right away? It works for new conversations (first block), but not for the existing conversations (second block)

以下代码适用于 addNewConvo(新对话),但不适用于 addMessagetoConversation(现有对话)。我以为我对两者都做了相同的过程,但我在第二部分中遗漏了一些东西。

  const addNewConvo = useCallback(
    (recipientId, message) => {
      const newConversations = conversations.map((convo) => {
        if (convo.otherUser.id === recipientId) {
          //  convo.messages.push(message);
          //  convo.latestMessageText = message.text;
          //  convo.id = message.conversationId;
          return {
            ...convo,
            messages: [...convo.messages, message],
            latestMessageText: message.text,
            id: message.conversationId
          }
        }
        return convo
      });
      setConversations(newConversations);
    },
    [setConversations, conversations]
  );

  const addMessageToConversation = useCallback(
    (data) => {
      // if sender isn't null, that means the message needs to be put in a brand new convo
      const { message, sender = null } = data;
      if (sender !== null) {
        const newConvo = {
          id: message.conversationId,
          otherUser: sender,
          messages: [message],
        };
        newConvo.latestMessageText = message.text;
        setConversations((prev) => [newConvo, ...prev]);
      }

      conversations.forEach((convo) => {
        if (convo.id === message.conversationId) {
          //  convo.messages.push(message);
          //  convo.latestMessageText = message.text;
          return {
            ...convo,
            messages: [...convo.messages, message],
            latestMessageText: message.text,
          }
        }
        return convo
      });
      setConversations(conversations);
    },    
    [setConversations, conversations]
  );

forEach 对数组中的每个元素执行回调,但不会改变数组或 return 任何内容。在你的情况下,你确实想改变它,所以你要做的是映射对话并在 id 匹配时更新对话。您还需要将地图的结果分配给一个新变量,因为它不会改变原始数组。

const newConversations = conversations.map((convo) => {
        if (convo.id === message.conversationId) {
          //  convo.messages.push(message);
          //  convo.latestMessageText = message.text;
          return {
            ...convo,
            messages: [...convo.messages, message],
            latestMessageText: message.text,
          }
        }
        return convo
      });
   setConversations(newConversations);