【问题标题】:How to get the element before the element in a map for the component in ReactJs如何在ReactJs中的组件的映射中获取元素之前的元素
【发布时间】:2021-06-12 05:53:49
【问题描述】:

我在地图中渲染组件,并为我的组件提供称为post 的数据对象。 这很好用

{feed.map((post, index) =>
        (
          <PostBasic post={post} key={post.id} creation={creation} />
        )
      )}

帖子中包含creationDatedescription 等信息...

我想在地图中使用之前帖子的creationDate 扩展每个PostBasic。首先我想做这样的事情,但它不起作用,post[index]post[index-1]

{feed.map((post, index) =>
            (
              <PostBasic post={post} postBefore={post[index-1]creationDate} key={post.id} creation={creation} />
            )
          )}

如果地图中有 5 个元素,我期待以下输出:

- PostBasic with post={post} and Date of now 
- PostBasic with post={post} and creationDate of post[0]
- PostBasic with post={post} and creationDate of post[1]
- PostBasic with post={post} and creationDate of post[2]
- PostBasic with post={post} and creationDate of post[3]

【问题讨论】:

  • 您将访问 feed[i-1] - 而不是发布。
  • 帖子保存在提要中。我试图更清楚地描述它。我已经在每个 PostBasic 中接收到帖子数据,我只是无法在 PostBasic 中接收到帖子的信息
  • 数组feed 是您要映射的对象,post 是当前值,index 是它的索引位置。我希望如果您正在映射提要,您将访问 feedi-1 - 这是您正在映射的数组。试试看。

标签: reactjs next.js


【解决方案1】:
export default function ComponentName({ feed }) {
  return (
    <>
        {feed.map((post, index) => {
          const postBefore =
            index == 0 ? new Date() : feed[index - 1].creationDate;
          return (
            <PostBasic
              post={post}
              postBefore={postBefore}
              key={post.id}
              creation={creation}
            />
          );
        })}
    </>
  );
}

你可以做这样的事情,你有正确的想法post[index - 1].creationDate你错过了dot,它应该是feed而不是post

【讨论】:

  • 您好,感谢您的帮助!缺少一些东西,如果我 console.log 之前的帖子,我得到一个未定义的
  • console.log 的提要如下:(3) [{...}, {...}, {...}] 0: {id: 5, createdAt: Fri Jun 11 2021 13:53: 37 GMT+0200 (Mitteleuropäische Sommerzeit), ...} 1: {id: 4, createdAt: Fri Jun 11 2021 13:52:06 GMT+0200 (Mitteleuropäische Sommerzeit), ...} length: 2 proto : 数组(0)
  • 对不起,我有一个错字,一切正常。非常感谢!
  • 确实告诉你使用feed[i-1]很高兴你把它整理好了。
【解决方案2】:

在渲染之前映射数据,像这样,

const postsWithDate = feed.map((post, i) => {
  if(i === 0) return {...post, creationDate: (new Date())};
  return {...post, creationDate: (feed[i - 1].creationDate)}
});

然后在渲染中使用这个,

{postsWithDate.map((post, index) =>
    (
      <PostBasic post={post} key={post.id} creationDate={creationDate} />
    )
  )}

希望它有效!

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2011-01-12
    • 2013-07-25
    • 2017-05-14
    • 2012-02-26
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多