How to iterate through an array with React (Rails)

限于喜欢 提交于 2021-02-10 05:14:39

问题


I just started to learn React and I am trying to figure out how to find a specific value I am looking for. Just like you have the each.do method in Ruby and you can iterate through an array, I'm trying to do that with React.

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

I am trying to access the thumbnail._url and when using the debugger, I am not able to access all the objects and images. I thought of this.props.gallery.object.thumbnail_url and other ideas but I am not really sure of the best way!


回答1:


Use Array.prototype.map() to map the data to react elements. Not that elements rendered in a loop require a unique identifier (keys), to make rerendering list more performant.

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>
    )
  }
}



回答2:


You can do something like this:

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>
    )
  }
}

You may have noticed the prop key={index}. If you omit that, you will see a warning:

Each child in an array or iterator should have a unique "key" prop

Actually it is not passed to the component as prop but is used by React to aid the reconciliation of collections. This way React can handle the minimal DOM change.



来源:https://stackoverflow.com/questions/40746168/how-to-iterate-through-an-array-with-react-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!