简体   繁体   中英

Loop does not work with react

My loop repetition does not work, I'm using React to render on the screen, but only one element appears and my array has 12 elements. Can someone tell me why?

 import React from 'react' import '../custom/style.css' export default props =>{ const renderRows = () =>{ const list = props.list || [] for (var i = 0; i < list.length; i++) { var obj = list[i]; return ( <div key={obj.id}> <p>{obj.title}</p> <img src={obj.images.normal} /> </div> ) } } return( <div id="demo"> {renderRows()} </div> ) } 

You're returning a <div> on the first loop iteration. You'll want to create an array and push all your elements there instead. I'd recommend using the map function ie

const renderRows = () => {
  const list = props.list || [];
  return list.map(obj => (
    <div key={obj.id}>
      <p>{obj.title}</p>
      <img src={obj.images.normal} />
    </div>
  ));
};

Mapping over the div s is easier. The loop return s after the first iteration, thus only one <div> .

import React from 'react'
import '../custom/style.css'

export default rows = () => {
  return (
    props.list && props.list.map(obj => {
      <div key={obj.id}>
        <p>{obj.title}</p> 
        <img src={obj.images.normal}/> 
      </div>
    })
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM