简体   繁体   English

如何使用 map function 打印子数组的项目

[英]how to print items of sub array using map function

This is the code i am trying to print out the comments through map function but cant figure out how:这是我试图通过 map function 打印出评论的代码,但无法弄清楚如何:

class Postcomment2 extends React.Component {
uploadcomment = () => {
  return this.props.post.comments.map((commentz) => {
    return <div>{this.props.post.comments["comment"]}</div>;
  }); /* How to access sub array of comments and print them all */
};

render() {
  return (
    <div>
      <div>{this.uploadcomment()}</div>
    </div>
  );
}
}

in this Post is the array of objects and the data is:在这篇文章中是对象数组,数据是:

{
imageUrl:
  "https://i.pinimg.com/originals/83/6c/8a/836c8a66349fecbc0a06c4cc3d41e031.jpg",
user: Users[0].user,
likes: 410,
caption:
  "Here at kingdom tower... #KSA #KingdomTower #React JS #This is getting too long #Peace",
profilepic: Users[0]["image"],
comments: [
  {
    user: "zoraiz",
    comment: "Nicee!"
  },
  {
    user: "asher",
    comment: "Alrightttt!!"
  },
  {
    user: "hamis",
    comment: "Interesting...."
  }
]

}, },

uploadcomment = () => {
    const { comments } = this.props.post;

    return (
      <div>
         {comments.map(comment => {
             console.log(comment.user, comment.comment)
             return true;
         })}
      </div>
    )

This should now print out every comment's user and comment.现在应该打印出每个评论的用户和评论。 Change the return to whatever JSX you wish to render.将返回更改为您希望呈现的任何 JSX。

Before, you were mapping over the comments, and every iteration you got 'commentz' which you weren't even using inside of the map.之前,您正在映射评论,每次迭代都会得到“commentz”,您甚至没有在 map 内部使用它。 This is the current 'comment' in the iteration of the map, so you basically have access to it and it's properties such as user and comment .这是 map 迭代中的当前“评论”,因此您基本上可以访问它以及它的属性,例如usercomment

When you tried to do this.props.post.comments["comment"] previously, this was saying basically, every iteration, get comments.comment, however, comments is an array not an object.当您之前尝试执行this.props.post.comments["comment"]时,这基本上是在说,每次迭代都会获取 comments.comment,但是,comments 是一个数组,而不是 object。

You need to first Traverse the Post array and after that traverse the subArray comment .您需要首先遍历Post数组,然后遍历 subArray comment Please find the codeSandbox link请找到codeSandbox链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM