循环遍历多个项目并渲染每个项目

时间:2016-12-10 23:40:56

标签: javascript reactjs

我遇到了绕着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>
            {for(var i=0; i<users.length; i++){
                <Welcome firstName={users[i].firstName} lastName={users[i].lastName}/>
            }}
        </div>
    )
}

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

2 个答案:

答案 0 :(得分:2)

尝试使用.map代替for循环。它通常更容易在React中使用:

&#13;
&#13;
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')
);
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

此外,由于它不是代码大墙而且您使用的是ES6,因此我允许自己重写整个代码,以向您展示“更好的方法”。

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')
);