array.map上的内部迭代,以便在不更改时显示该值一次

发布于 2025-02-13 18:11:17 字数 804 浏览 0 评论 0原文

我正在构建一个简单的新闻显示,其中日期显示在排版元素上,而在此版式下,每名诺夫达(Novedad)都是新的。 我正在尝试迭代,因此日期是从第一个新闻中获得的(该新闻已经按日期desc订购)。因此,虽然其他新闻的日期相同,但不应出现具有日期的新标题框。

但是,我不知道如何处理该编程。请注意,我正在使用React,并且正在尝试使用条件渲染。

简而言之,我试图通过日期与另一个元素一起显示一系列对象,显示此日期。

以下代码显示了上面的日期标题的每个新闻,这不是意图结果。

novedades.map((novedad)=>{
        return(
        <>  
            <Typography variant="h6" component="div">
                {moment(novedad.date).format("dddd, DD/MM/YYYY")}
            </Typography>

            /*The following element should be iterated so while novedad.date does not change it does not exit the loop*/
            <Novedad key={novedad.id} tipo={novedad.tipo} creador={novedad.creado_por} fecha={novedad.date} contenido={novedad.contenido_html}/>
        </>
)})

I'm building a simple News display, where the date is displayed on a Typography element and below of this Typography each Novedad is a new.
I'm trying to iterate so the date is got from the first news (the news are already ordered by date DESC). so, while other news have the same date, no new title box with the date should appear.

However I don't know how to approach this programming. Notice I'm using React and I'm trying to use conditional rendering.

In short, I'm trying to display an array of objects grouping them by date with another element showing this date.

The following code displays each news with a date title above, which is not the intented result.

novedades.map((novedad)=>{
        return(
        <>  
            <Typography variant="h6" component="div">
                {moment(novedad.date).format("dddd, DD/MM/YYYY")}
            </Typography>

            /*The following element should be iterated so while novedad.date does not change it does not exit the loop*/
            <Novedad key={novedad.id} tipo={novedad.tipo} creador={novedad.creado_por} fecha={novedad.date} contenido={novedad.contenido_html}/>
        </>
)})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多情出卖 2025-02-20 18:11:18

这是您可以做到这一点的一种方法:

const dates=array.map(novedad=>novedad.date)
const uniqueDates=[... new Set(dates)]

...其余代码...

{uniqueDates.map(date=>{
return (
  <Typography variant="h6" component="div">
                {moment(date).format("dddd, DD/MM/YYYY")}
  </Typography>

{novedades.map(novedad=>{
 return novedad.date==date&&<Novedad key={novedad.id} tipo={novedad.tipo} creador={novedad.creado_por} fecha={novedad.date} contenido={novedad.contenido_html}/>
})})}

This is one way you could do this:

const dates=array.map(novedad=>novedad.date)
const uniqueDates=[... new Set(dates)]

... rest of code ...

{uniqueDates.map(date=>{
return (
  <Typography variant="h6" component="div">
                {moment(date).format("dddd, DD/MM/YYYY")}
  </Typography>

{novedades.map(novedad=>{
 return novedad.date==date&&<Novedad key={novedad.id} tipo={novedad.tipo} creador={novedad.creado_por} fecha={novedad.date} contenido={novedad.contenido_html}/>
})})}
阳光下的泡沫是彩色的 2025-02-20 18:11:18

您可以在渲染之前尝试按日期对新闻进行分组。
一个简单的解决方案将是使用一个简单的键值对方法,例如One Bellow

const [groupedNewsByDate, setGroupedNewsByDate] = useState(null);

useEffect(() => {
  // fake HTTP request
  Promise.resolve([
  {
    date: "2022-07-07T14:50:10.489Z",
    id: 4,
    content: "News 4"
  },
  {
    date: "2022-07-07T14:50:10.489Z",
    id: 3,
    content: "News 3"
  },
  {
    date: "2022-07-06T14:50:10.489Z",
    id: 2,
    content: "News 2"
  },
  {
    date: "2022-07-05T14:50:10.489Z",
    id: 1,
    content: "News 1"
  }
]).then((entries) => {
  // grouping news that have the same date
  setGroupedNewsByDate(
    entries.reduce((map, item) => {
      const items = map[item.date] || [];
      items.push(item);
      map[item.date] = items;
      return map;
    }, {})
  );
});
}, []);

function renderNews() {
  const dates = Object.keys(groupedNewsByDate);
  // render fallback ui if no news
  if (dates.length === 0) {
    return <span>No news</span>;
  }

// render news grouped by date
return dates.map((date) => (
  <section key={date} aria-labelledby={date}>
    <h2 id={date}>{new Date(date).toLocaleDateString()}</h2>
    {groupedNewsByDate[date].map((item) => (
      <div key={item.id}>{item.content}</div>
    ))}
  </section>
));
}

Live Demo:
https://codesandbox.io/s/reverent-pare/reverent-pare/reverent-pare/reverent-pare -5m9mme?file =/src/app.js

You can try grouping the news by date before rendering them.
A simple solution will be to use a simple key-value pair approach like the one bellow

const [groupedNewsByDate, setGroupedNewsByDate] = useState(null);

useEffect(() => {
  // fake HTTP request
  Promise.resolve([
  {
    date: "2022-07-07T14:50:10.489Z",
    id: 4,
    content: "News 4"
  },
  {
    date: "2022-07-07T14:50:10.489Z",
    id: 3,
    content: "News 3"
  },
  {
    date: "2022-07-06T14:50:10.489Z",
    id: 2,
    content: "News 2"
  },
  {
    date: "2022-07-05T14:50:10.489Z",
    id: 1,
    content: "News 1"
  }
]).then((entries) => {
  // grouping news that have the same date
  setGroupedNewsByDate(
    entries.reduce((map, item) => {
      const items = map[item.date] || [];
      items.push(item);
      map[item.date] = items;
      return map;
    }, {})
  );
});
}, []);

function renderNews() {
  const dates = Object.keys(groupedNewsByDate);
  // render fallback ui if no news
  if (dates.length === 0) {
    return <span>No news</span>;
  }

// render news grouped by date
return dates.map((date) => (
  <section key={date} aria-labelledby={date}>
    <h2 id={date}>{new Date(date).toLocaleDateString()}</h2>
    {groupedNewsByDate[date].map((item) => (
      <div key={item.id}>{item.content}</div>
    ))}
  </section>
));
}

Live demo:
https://codesandbox.io/s/reverent-pare-5m9mme?file=/src/App.js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文