【问题标题】:How to iterate over an array that's inside an object in React JS如何遍历 React JS 中对象内部的数组
【发布时间】:2025-12-31 20:45:02
【问题描述】:

想象一下我有一个这样的对象数组:

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

我想使用 props 将 images 数组中的每个图像分配给一个名为 CarrouselItem 的 React 组件:

class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}

然后将其放入名为 Carrousel 的父组件中,在该组件中循环对象并返回其中的图像,然后将其放置在 CarrouselItem 组件中:

class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}
      </div>
    )
  }
}

我预计会发生什么

map 函数应该遍历所有对象(在这种情况下,只是其中一个),然后创建 X 个 CarrouselItem 组件,每个组件都有一个 &lt;img&gt;,它取自 images 数组。

实际发生的情况

不幸的是,我只得到数组中的第一项(在本例中为'http://lorempixel.com/400/400/sports/')。

有人能解释一下我哪里出错了吗?

Link to CodePen.

【问题讨论】:

    标签: javascript arrays reactjs object


    【解决方案1】:

    首先您需要遍历 chefs 数组,然后是单个图像。

    const chefs = [
      {
        key: 1,
        images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
      }
    ]
    
    class Carrousel extends React.Component {
      render() {
        return (
          <div>
            <h4>Slide image</h4>
            {chefs.map((chef, i)=>(
              <div key={i}>
                {chef.images.map((image,index)=>(
                  <CarrouselItem imageUrl={image} key={index} />
                ))}
              </div>  
            ))}
            ))
          </div>
        )
      }
    }
    
    class CarrouselItem extends React.Component {
      render() {
    
        return (
          <div>
            <img src={this.props.imageUrl} />
          </div>
        )
      }
    }
    
    ReactDOM.render(<Carrousel />,document.getElementById("app"))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>

    【讨论】:

    • 感谢 anuragasaurus,我确实考虑过这样做,虽然我不知道为什么但它只是“感觉”对我来说是一种不好的做法......虽然它现在有效,所以谢谢你!我会选择这个作为正确答案(如果可以的话),如果发布了更好的解决方案,然后修改它。再次感谢!
    • @A7DC 为什么你觉得这是一个不好的做法?您的chefs 数组有images 数组,因此您需要迭代两次。
    • 好的,太棒了。我不确定,只是当我想到这样做时,它似乎很冗长,我认为会有一种更简洁的方式来做这件事——但你们两个似乎没有想出类似的解决方案。再次感谢!
    【解决方案2】:

    它只给你一个项目的原因是因为你正在映射一个厨师而不是他的图像。所以你只迭代一次。相反,您只想像chefs.images.map

    那样映射图像
    const chefs = [
      {
        key: 1,
        images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
      }
    ]
    
    class Carrousel extends React.Component {
      render() {
        const elems = [];
        chefs.forEach( (chef) => {
            chef && chef.images.forEach( (image, j) => {
                elems.push(<CarrouselItem imageUrl={image} key={i} />)
            })
        })
        return (
          <div>
            <h4>Slide image</h4>
            {elems}
          </div>
        )
      }
    }
    

    我建议您制作一个厨师组件,它可以呈现厨师信息、姓名、年龄、位置、餐厅...等内容,并为每个厨师提供带有图像的轮播。

    【讨论】:

    • 回复得很快,谢谢!虽然这就是我之前的想法,尽管每当我尝试映射 chefs.images 时,它都会返回 TypeError: undefined is not an object (evalating 'chefs.images.map')。
    • @A7DC 听起来您在某处有一些无效数据。我会在编辑时在一秒钟内处理这个问题
    • @JohnRuddell 不需要遍历 chefs 数组来获取个人厨师元素。
    • 谢谢伙计,你是个传奇。我不确定哪个是更好的答案(你的或 anuragasaurus),所以我暂时将他的答案作为“正确”答案,直到其他人审查了这两个 cmets。但再次感谢人!我真的很感激?
    • @A7DC 不用担心 :) 我个人喜欢我的答案,因为它更具可读性,但两者都是完全可以接受的答案 :) 我还添加了关于如何更好地布置数据的建议:)
    【解决方案3】:

    实际上它的主厨对象索引是一个,所以你首先使用chefs.images.map

    {chefs[0].images.map((image, index) => {
              return <CarrouselItem imageUrl={image} />
            })}
    

    【讨论】:

    • 与上面的评论一样:每当我尝试映射 chefs.images 时,它都会返回 TypeError: undefined is not an object(评估“chefs.images.map”)。不知道这是为什么?顺便谢谢你的回复!
    • 你可以使用子索引 chefs[0]
    • 你是对的,但不幸的是,如果将多个厨师添加到 chefs 数组中,这会中断,对吧?