const robots = [
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
},
{
id: 2,
name: 'Ervin Howell',
username: 'Antonette',
},
{
id: 3,
name: 'Clementine Bauch',
username: 'Samantha',
},
{
id: 4,
name: 'Patricia Lebsack',
username: 'Karianne',
},
{
id: 5,
name: 'Chelsey Dietrich',
username: 'Kamren',
},
{
id: 6,
name: 'Mrs. Dennis Schulist',
username: 'Leopoldo_Corkery',
},
{
id: 7,
name: 'Kurtis Weissnat',
username: 'Elwyn.Skiles',
},
{
id: 8,
name: 'Nicholas Runolfsdottir V',
username: 'Maxime_Nienow',
},
{
id: 9,
name: 'Glenna Reichert',
username: 'Delphine',
},
{
id: 10,
name: 'Clementina DuBuque',
username: 'Moriah.Stanton',
}
];
let cardComp = robots.forEach((element,index)=> {
return (<Card id = {robots[index].id} Name = {robots[index].name}
user ={robots[index].username} mail = {robots[index].email}/>)
});下面的代码在react.js中不起作用,但是当我用地图替换forEach循环时,同样的代码工作得很好。为什么它不能与forEach循环一起工作?当我尝试使用普通的javascript从对象数组中获取值时,它工作得很好,并且我能够获得数组中的所有值。但它不能在使用forEach循环的react.js中工作。
发布于 2018-06-26 20:23:24
let cardComp = robots.forEach((element,index)=> {
return (<Card id = {robots[index].id} Name = {robots[index].name}
user ={robots[index].username} mail = {robots[index].email}/>)
});javascript中的forEach不返回任何内容。
而是使用返回新数组map
let cardComp = robots.map((element) => {
return (<Card id={element.id} Name={element.name} user={element.username} mail={element.email}/>)
});请参阅有关forEach的MDN原型信息

和 map
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])

https://stackoverflow.com/questions/51042346
复制相似问题