如何使用 React (Rails) 遍历数组

IT技术 javascript arrays debugging reactjs
2022-07-21 01:27:08

我刚开始学习 React,我试图弄清楚如何找到我正在寻找的特定值。就像你在 Ruby 中有 each.do 方法并且你可以遍历一个数组一样,我正在尝试用 React 来做到这一点。

class Gallery extends React.Component {
  render () {
    // debugger;
    return (
      <div>
      <img> {this.props.gallery.thumbnail_url} </img>
      </div>
    )
  }
}

我正在尝试访问 thumbnail._url 并且在使用调试器时,我无法访问所有对象和图像。我想到了 this.props.gallery.object.thumbnail_url 和其他想法,但我不确定最好的方法!调试器信息

2个回答

用于Array.prototype.map()将数据映射到react元素。并不是说在循环中呈现的元素需要唯一标识符(keys),以使重新呈现列表更具性能。

class Gallery extends React.Component {
  render () {
    const { gallery = [] } = this.props; // destructure the props with a default (not strictly necessary, but more convenient) 

    return (
      <div>
      {
       gallery.map(({ id, thumbnail_url }) => (
         <img key={ id } src={ thumbnail_url } />
       ))
      }
      </div>
    )
  }
}

你可以这样做:

class Gallery extends React.Component {
  render () {
    // initialize 'images' to empty array if this.props.gallery is undefined
    // other wise 'images.map' will throw error
    const images = this.props.gallery || []; 

    return (
      <div>
        {images.map((image, index) => <img src={image.thumbnail_url} key={index} />)}
      </div>
    )
  }
}

你可能已经注意到了 prop key={index}如果你忽略它,你会看到一个警告:

数组或迭代器中的每个孩子都应该有一个唯一的“key”props

实际上,它并没有作为 prop 传递给组件,而是被 React 用来帮助协调集合。这种方式 React 可以处理最小的 DOM 更改。