【问题标题】:Mapping through array of objects to display images通过对象数组映射以显示图像
【发布时间】:2020-06-01 20:00:27
【问题描述】:

我正在尝试映射一组对象以显示图像。这是我的代码:

import React from 'react';
import photos from '../photo-store';

class Landing extends React.Component {
  render() {
    const photoDisplay = Object.keys(photos).map((photo, i) => {
      return <img key={i} src={`.${photos[photo][i].src}`} alt='headshot'/>
    })
    console.log('photoDisplay', photoDisplay)
    return (
      <div>
        <p>Photos will go here</p>
        {photoDisplay}
      </div>
    )
  }
}

export default Landing;

当我 console.log 时,src 值是正确的,但由于某种原因,我只是得到了我的 alt 信息渲染,它并没有遍历数组中的所有对象。任何关于这里可能发生的事情的指示都会很棒。提前感谢您的帮助!

这是“照片”中的内容的 sn-p:

"photos": [
    {
      id: 1,
      name: "AmberB",
      src: "./images/AmberB.jpg"
    },
    {
      id: 2,
      name: "AmberR",
      src: "./images/AmberR.jpg"
    }
  ]
}

【问题讨论】:

    标签: javascript arrays reactjs mapping


    【解决方案1】:

    您在return 语句中犯了一个小错误。如果你有 src 属性 ${photos[photo].src} 而不是 photos[photo][i].src 那么它应该可以工作。

    const photoDisplay = Object.keys(photos).map((photo, i) => {
       return <img key={i} src={`${photos[photo].src}`} alt='headshot'/>
    })
    

    也请考虑删除.,但不确定。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2019-11-21
      • 2022-10-06
      • 2022-01-25
      • 1970-01-01
      • 2023-03-18
      • 2020-10-24
      • 1970-01-01
      相关资源
      最近更新 更多