【问题标题】:Nested array .map without looping the parent array嵌套数组 .map 不循环父数组
【发布时间】:2017-07-14 10:39:10
【问题描述】:

示例:https://jsfiddle.net/zidski/a0ez5sy9/1/

我创建了一个名为 ProjectAPI 的 JSON 对象。

  const ProjectAPI = {
      projects: [
        { 
          name: "PROJECT NAME", 
          thumbnail: "imageURL",
          image: [
            "imageURL",
            "imageURL",
            "imageURL" 
          ]
        },{ 
          name: "PROJECT NAME", 
          thumbnail: "imageURL",
          image: [
            "imageURL",
            "imageURL",
            "imageURL" 
          ]
        }],
  all: function() { return this.projects},
  get: function(id) {
    const isProject = p => p.number === id
    return this.projects.find(isProject)
  }
    }

然后我使用 .map 来获取嵌套图像:

 {
        ProjectAPI.all().map(function(item, index) {
          return <img className="img" key={index} src={item.image[index]} />
        })
      }

但似乎是循环遍历父数组,所以我最终得到 6 个图像而不是 3 个(在 jsfiddle 示例中边框红色)

我怎样才能只定位嵌套图像?

【问题讨论】:

  • so I end up with 6 images instead of 3 你的意思是3 images instead of 6
  • 是 3 张图片而不是 6 张。

标签: javascript arrays reactjs


【解决方案1】:

由于图像又是一个数组,所以您还需要在其上运行 map。

这样写:

{
    ProjectAPI.all().map((item, index) => {
        return item.image.map((el,j) => <img className="img" key={j} src={el} />)
    })
}

更新:

你想要第一个对象的前三张图片,所以你不需要使用嵌套地图,这样写:

ProjectAPI.all()[0].image.map((el,i) => <img className="img" key={i} src={el} />)

Fiddle with all the images.

Fiddle with only three images.

【讨论】:

  • 也许 item.image.map ?
  • @Jonasw 对不起我的错误,更新了答案谢谢:)
  • 如果我只想获取前 3 张图片怎么样,现在它会获取所有图片
  • projects 数组的第一个对象的前三个图像?
  • 是的,因为每个对象在我的应用程序中都是不同的页面
【解决方案2】:

问题是这样的:

src={item.image[index]}

indexprojects 数组中的索引,它来自0..n,其中nprojects 数组中的对象数。对于第四项,您尝试输出projects[3].image[3],如果该图像数组仅包含三个图像,则什么都不是。

如果您想输出每个项目的所有三张图像,您还需要遍历各个图像。

【讨论】:

    【解决方案3】:

    需要在图像对象中指定图像 url 的索引。因为在代码的 map 函数中指定增量数 0 到 5(数据的长度)。但是您的图像数组没有 map 函数的索引值。

    var Hello = React.createClass({
      render: function() {
        return (
        <div>
         {
            ProjectAPI.all().map(function(item, index) {
              return <img className="img" key={index} src={item.image[0]} />
            })
          }
        </div>
        );
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2022-05-12
      • 2013-09-22
      • 1970-01-01
      • 2019-01-14
      • 2015-07-17
      • 2020-06-02
      • 2013-09-18
      • 1970-01-01
      相关资源
      最近更新 更多