简体   繁体   中英

Looping through multiple items and rendering each

I'm having issues with wrapping my head around React to loop through things to render a component multiple times in a row. Here's what I've got but it's not working. Some pointers as to what I'm doing wrong and a better way of doing it would be appreciated, thanks!

const users = [
    {
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }, {
        "firstName": "Peter",
        "lastName": "Jones"
    }
];

function Welcome(props) {
  return <h1>Hello, {props.firstName} {props.lastName}</h1>;
}

function allUsers(){
    return (
        <div>
            {for(var i=0; i<users.length; i++){
                <Welcome firstName={users[i].firstName} lastName={users[i].lastName}/>
            }}
        </div>
    )
}

ReactDOM.render(
  allUsers(),
  document.getElementById('root')
);

Try using .map instead of the for loop. It's usually easier to use in React:

 const users = [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ]; function Welcome(props) { return <h1>Hello, {props.firstName} {props.lastName}</h1>; } function allUsers(){ return ( <div> {users.map(function(user) { return <Welcome key={user.firstName} firstName={user.firstName} lastName={user.lastName}/> })} </div> ) } ReactDOM.render( allUsers(), document.getElementById('View') ); 
 <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="View"></div> 

Also since it's not big wall of code and you are using ES6 I allowed myself to rewrite entire code to show you "a better way of doing it".

const users = [
    {
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }, {
        "firstName": "Peter",
        "lastName": "Jones"
    }
];

const Welcome = ({firstName, lastName}) => <h1>Hello, {firstName} {lastName}</h1>;

const AllUsers = () => (
        <div>
          {
            users.map((user, key) => <Welcome key={key} firstName={user.firstName} lastName={user.lastName} />)
          }
        </div>
)

ReactDOM.render(
  <AllUsers />,
  document.getElementById('root')
);

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