How do i use for loops with react? [duplicate]

好久不见. 提交于 2019-12-21 07:15:06

问题


I'm very new to react and all I really want is a simple for loop that creates menuitem elements for each user in my array with the title of it being their firstname. So this is how I would write it, but I have no clue of how to do this in react. I think it should be with a map maybe but I cant seem to get it to work either hopefully anyone out here can help me.

for (var i = 0; i < Users.length; i++) {
  <MenuItem eventKey=[i]>User.firstname[i]</MenuItem>
}

回答1:


The render method of your component, or your stateless component function, returns the elements to be rendered.

If you want to use a loop, that's fine:

render() {
    let menuItems = [];
    for (var i = 0; i < Users.length; i++) {
        menuItems.push(<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>);
    }
    return <div>{menuItems}</div>;
}

More common would be to see a more functional style, such as using a map to return the array of elements:

render() {
    return <div>
    {
        Users.map((user, i) =>
            <MenuItem eventKey=[i]>User.firstname[i]</MenuItem>)
    }
    </div>;
}

Note that in either case, you are missing the key property from each element of your array, so you will see warnings. Each element in an array should have a unique key, preferably some form of ID rather than just the array index.




回答2:


With map you can do:

Users.map((user, index) => (
  <MenuItem eventKey={index}>user.firstname</MenuItem>
));


来源:https://stackoverflow.com/questions/46908480/how-do-i-use-for-loops-with-react

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