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

如何在React中按最新日期排序API数据并渲染卡片

解决方案

要实现按最新日期排序后渲染卡片,你需要在渲染前对数据数组进行排序,而不是在单个元素上操作。以下是具体修改步骤:

1. 先过滤再排序数据

在渲染卡片前,先筛选出需要展示的条目(showOnHomepage === "yes"),再按publishedDate降序排序(最新日期在前):

// 先过滤出要展示的条目,再按日期降序排序
const sortedNewsItems = filteredCat?.filter(item => item.showOnHomepage === "yes")
  .sort((a, b) => new Date(b.publishedDate) - new Date(a.publishedDate));

2. 优化分类名称获取逻辑

原代码用map获取分类名称会返回包含undefined的数组,改用find直接获取对应名称更合理:

// 用find替代map,直接获取匹配的分类名称
const showCat = news.find(getid => getid.id === list.categoryID)?.name || '未知分类';

3. 修改渲染逻辑

用处理好的排序后数组进行渲染,去掉map里的条件判断,让代码更简洁:

修改后的完整渲染代码片段

{sortedNewsItems && sortedNewsItems.map((list) => {
  const date = format(
    new Date(list.publishedDate),
    "EEE dd MMM yyyy"
  );
  const showCat = news.find(getid => getid.id === list.categoryID)?.name || '未知分类';

  return (
    <Card
      className=" extraCard col-lg-3"
      style={{ width: "" }}
      id={list.categoryID}
      key={list.id} // 务必添加唯一key,避免React警告
    >
      <Card.Img
        variant="top"
        src={list.urlToImage}
        alt="Image"
      />
      <Card.Body>
        <Card.Title className="textTitle">
          {list.title}
        </Card.Title>
        <Card.Text></Card.Text>
        <small className="text-muted d-flex">
          <FaRegCalendarAlt
            className="m-1"
            style={{ color: "#0aceff" }}
          />
          {date}
        </small>

        <div
          style={{ color: "#0aceff" }}
          className="d-flex justify-content-between"
        >
          <Button variant="" className={classes["btn-cat"]}>
            {showCat}
          </Button>
          <div>
            <FaRegHeart />
            <p>
              <FaLink />
              <BrowserRouter>
              </BrowserRouter>
              <a
                href="/Newsitem"
                target="_blank" // 修正target属性,原写法无效
                rel="noopener noreferrer"
              >
                <button>Go to another page</button>
              </a>
            </p>
          </div>
        </div>
      </Card.Body>
    </Card>
  );
})}

关键说明

  • 排序逻辑:new Date(b.publishedDate) - new Date(a.publishedDate) 实现降序,把最新日期的条目放在数组前面;如果要升序则反过来用a - b。
  • 必须给map返回的Card组件添加唯一key属性(比如用list.id),避免React渲染警告。
  • 修正了原代码中target属性的错误写法,target="/src/components/News/Newsitem"是无效的,若要在新窗口打开应使用target="_blank"。

内容的提问来源于stack exchange,提问作者Farah Fahmy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:45:32