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

React中Array.map遍历按日期分组 同日期仅显示一次日期标题

同日期新闻不重复渲染日期标题实现方案

你的数据已经提前按日期倒序排列,不需要做复杂的全量分组转换,直接在遍历阶段加条件判断即可实现需求,性能比预处理分组更高。

核心逻辑

  • 遍历原始数组时,给map传入索引参数
  • 统一格式化当前项和上一项的日期(和标题展示的日期格式保持一致,避免原始日期值带时分秒、时区偏差导致同一天被判定为不同日期)
  • 仅当当前项是数组第一条,或者当前项日期和上一项日期不一致时,才渲染日期标题块
  • 注意遍历场景下不要用短语法空标签<></>,换成React.Fragment才能绑定key,避免React抛出key警告

修正后代码

novedades.map((novedad, index) => {
  // 统一格式化日期,和标题展示规则完全一致
  const currentDate = moment(novedad.date).format("dddd, DD/MM/YYYY");
  const prevDate = index === 0 
    ? null 
    : moment(novedades[index - 1].date).format("dddd, DD/MM/YYYY");
  // 判断是否需要渲染当前位置的日期标题
  const showDateTitle = index === 0 || currentDate !== prevDate;

  return (
    <React.Fragment key={novedad.id}>
      {showDateTitle && (
        <Typography variant="h6" component="div">
          {currentDate}
        </Typography>
      )}
      <Novedad
        tipo={novedad.tipo}
        creador={novedad.creado_por}
        fecha={novedad.date}
        contenido={novedad.contenido_html}
      />
    </React.Fragment>
  )
})

可选方案(适合需要组级容器的场景)

如果你后续需要给每个日期组加外层包裹样式、组折叠/展开等交互,可以先把原始数组预处理为分组结构再遍历:

// 预处理为按日期分组的结构
const groupedList = novedades.reduce((acc, cur) => {
  const curDate = moment(cur.date).format("dddd, DD/MM/YYYY");
  const lastGroup = acc.at(-1);
  if (lastGroup?.date === curDate) {
    lastGroup.news.push(cur);
  } else {
    acc.push({ date: curDate, news: [cur] });
  }
  return acc;
}, []);

// 双层遍历渲染
return (
  <div className="news-container">
    {groupedList.map(group => (
      <section className="date-group" key={group.date}>
        <Typography variant="h6" component="div">
          {group.date}
        </Typography>
        {group.news.map(item => (
          <Novedad
            key={item.id}
            tipo={item.tipo}
            creador={item.creado_por}
            fecha={item.date}
            contenido={item.contenido_html}
          />
        ))}
      </section>
    ))}
  </div>
)

内容的提问来源于stack exchange,提问作者Germán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 18:45:41