遍历React.js中的嵌套对象

时间:2020-10-12 14:55:25

标签: arrays reactjs object react-props

我从我的API中获得了这个json:

 {
  posts: [
    {
      id: 1,
      title: 'Titel one',
      image: {
        image: "https://imagepath"
        crops: [
          {
            height: 150
            path: "https://imagepath"
            type: "small"
            width: 200
          },
          {
            height: 350
            path: "https://imagepath"
            type: "large"
            width: 600
          }

        ]
      }
    },
    {
      id: 2,
      title: 'Titel two',
      image: {
        image: "https://imagepath"
        crops: [
          {
            height: 150
            path: "https://imagepath"
            type: "small"
            width: 200
          },
          {
            height: 350
            path: "https://imagepath"
            type: "large"
            width: 600
          }
        ]
      }
    }
  ]
}

在数组的子List.js子项map中:

function List(props) {
  return (
    <div>
      {props.posts.map(post => (
        <Card key={post.id} image={post.image} title={post.titel} />
      ))}
    </div>
  )
}

呈现idtitleimage的效果很好。

但是我需要通过一种作物类型(例如small)绘制特定的图像路径。我该如何实现?

更新

我在组件中添加了以下内容:

function Card({ image, title }) {
  return (
    <div>
      <figure>
    {image.crops
      .filter(cropType => cropType.type === 'small')
      .map(filteredURL => (
        <img src={filteredURL.path} alt={title} />
      ))}
  </figure>
      <div>
        <h2>
          {title}
        </h2>
      </div>
    </div>
  )
}

这是一个好的干净的解决方案吗?还是有更好的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作。我相信您想要与small裁剪对应的图像对象。我将您的组件分为两部分,以进一步分离问题。

// The Card component should be able to handle nullish values or have this component check to see if there is an image, title, etc. for each index.
function ListItem({ id, image, title }) {
  const croppedImage = image.crops.find((crop) => crop.type === 'small');
  return <Card image={croppedImage} key={id} title={title} />;
};

function List({ posts }) {
  const items = posts.map((post) => <ListItem {...post} />);
  return <div>{items}</div>;
};