You need to enable JavaScript to run this app. React JS开发类WhatsApp Web聊天的数组消息映射渲染异常问题
优惠活动
大模型
产品
解决方案
定价
更多

React JS开发类WhatsApp Web聊天的数组消息映射渲染异常问题

聊天消息渲染的修复实现

核心问题修正方向

  • 原渲染逻辑没有根据消息自带的sender标识区分消息归属,所有消息固定显示联系人名称,完全无法区分对话双方
  • 列表渲染未添加唯一key属性,触发React列表渲染警告
  • 直接对chatArr[fullChat]取值未做兜底保护,会话数据缺失时会直接触发运行时白屏
  • 未对不同发送方的消息做样式差异化,无法实现类WhatsApp的左右分栏气泡效果
  • 原初始状态定义存在语法遗漏,缺少数组和函数调用的闭合括号,本身就无法正常运行

初始状态修正后的可运行结构

const [chatArr, setChatArr] = useState([
  {
    id: "v7fAa5OltrU=",
    from: "Shai Dayan",
    newMsg: {
      msgs: [
        {sender: 0, text:"Hello there, I'm using Chat !"},
        {sender: 1, text:"Hello there, I'm using Chat !"}
      ]
    },
    group: false,
    players: ['Shai Dayan']
  }
])

规范的消息对象结构

每个会话下的msgs数组中,单条消息的标准结构为:

{
  msgId: "消息唯一标识", // 用于列表渲染的key
  sender: 0, // 约定规则:0 = 当前登录用户发送,1 = 会话联系人发送
  text: "消息文本内容",
  timestamp: 1699999999 // 消息发送时间戳,用于后续排序
}

发送方标识的数值规则可以自定义,只要整个应用全局统一即可,不需要固定用0/1对应固定身份。

可正常运行的渲染代码

// 先安全读取当前打开的会话对象,避免取值报错
const currentChat = chatArr[fullChat];

// 渲染消息列表
{currentChat?.newMsg?.msgs?.map((element, index) => {
  // 根据sender值判断消息归属
  const isOwnMessage = element.sender === 0;
  return (
    <div 
      // 优先用消息自带的唯一ID当key,无ID时临时用索引兜底
      key={element.msgId ?? index}
      className={`speech-bubble ${isOwnMessage ? "speech-bubble--own" : "speech-bubble--other"}`}
    >
      <div className="text-msg">
        <div className='name-msg'>
          {/* 仅展示对方发送消息的昵称,自己发送的消息不需要重复展示昵称 */}
          {!isOwnMessage && <span className='from'>{currentChat.from}</span>}
          <br/>
          {element.text}
        </div>
      </div>
    </div>
  )
})}

消息追加的标准写法

必须遵循React状态的不可变更新规则,不要直接修改原状态数组,给指定会话追加新消息的实现为:

const handleSendMessage = (messageText) => {
  // 构建新的消息对象
  const userSentMsg = {
    msgId: `msg_${Date.now()}`,
    sender: 0,
    text: messageText,
    timestamp: Date.now()
  }

  setChatArr(prevChatList => {
    // 复制旧的会话数组,避免直接修改原状态
    const newChatList = [...prevChatList];
    // 给当前打开的会话追加新消息
    newChatList[fullChat] = {
      ...newChatList[fullChat],
      newMsg: {
        msgs: [...newChatList[fullChat].newMsg.msgs, userSentMsg]
      }
    }
    return newChatList;
  })
}

配套样式参考

实现类WhatsApp的气泡布局可添加如下CSS规则:

.speech-bubble {
  display: flex;
  margin: 8px 16px;
}
/* 自己发的消息靠右对齐 */
.speech-bubble--own {
  justify-content: flex-end;
}
/* 对方发的消息靠左对齐 */
.speech-bubble--other {
  justify-content: flex-start;
}
.text-msg {
  max-width: 70%;
  padding: 8px 12px;
  border-radius: 12px;
  line-height: 1.5;
}
.speech-bubble--own .text-msg {
  background: #d9fdd3;
}
.speech-bubble--other .text-msg {
  background: #fff;
}

内容的提问来源于stack exchange,提问作者Sahar Biton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 16:06:08