[英]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. 我在把头缠在React上以循环遍历以多次渲染一个组件时遇到了问题。 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. 尝试使用.map
而不是for循环。 It's usually easier to use in React: 通常在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". 另外,由于它不是一堆繁琐的代码,并且您正在使用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')
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.