You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Firestore聊天应用:消息时间显示报错与实现需求

解决Firestore聊天消息时间渲染报错及实现WhatsApp式时间显示

报错原因

你遇到的Objects are not valid as a React child错误,是因为Firestore返回的date字段是Timestamp对象(包含seconds和nanoseconds两个键),React无法直接渲染这种复杂对象,必须先转换为可读的字符串格式。

解决方案

1. 基础修复:转换Timestamp为时间字符串

发送数据的代码无需修改(Timestamp.now()是正确的存储方式),只需在渲染时将Timestamp转换为Date对象,再格式化为时分格式:

<div>
  <p>
    {message.text}
    <span>
      {message.date && (
        <span>{new Intl.DateTimeFormat('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        }).format(message.date.toDate())}</span>
      )}
    </span>
  </p>
  {message.img && <img src={message.img} alt="" />}
</div>

2. 进阶实现:WhatsApp式智能时间显示

如果要实现类似WhatsApp的时间显示逻辑(今天显示时分、昨天显示「昨天+时分」、更早显示完整日期+时分),可以写一个辅助函数:

// 格式化消息时间的辅助函数
const formatMessageTime = (timestamp) => {
  const messageDate = timestamp.toDate();
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const msgDateOnly = new Date(messageDate.getFullYear(), messageDate.getMonth(), messageDate.getDate());

  // 今天的消息:显示时分
  if (msgDateOnly.getTime() === today.getTime()) {
    return new Intl.DateTimeFormat('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).format(messageDate);
  }

  // 昨天的消息:显示「昨天 时分」
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  if (msgDateOnly.getTime() === yesterday.getTime()) {
    return `昨天 ${new Intl.DateTimeFormat('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).format(messageDate)}`;
  }

  // 更早的消息:显示完整日期+时分
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  }).format(messageDate);
};

然后在渲染时调用该函数:

<div>
  <p>
    {message.text}
    <span>
      {message.date && <span>{formatMessageTime(message.date)}</span>}
    </span>
  </p>
  {message.img && <img src={message.img} alt="" />}
</div>

内容的提问来源于stack exchange,提问作者Naval Nehra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:56