Reactjs 地图有效,但 forEach 无效 [英] Reactjs map works but forEach doesn't
问题描述
我正在努力理解 forEach 和 map 之间的区别.在下面的渲染函数中,如果 'forEach' 被替换为 'map',它就可以工作.我不明白为什么它不适用于forEach".{item.id} 和 {item.text} 都存在于这两种方法中.那么,为什么在使用 'forEach' 时没有设置 'TodoItem' 的道具?
I'm struggling to understand the difference between forEach and map. In the following render function if the 'forEach' is replaced with 'map' it works. I don't understand why it doesn't work with the 'forEach'. Both {item.id} and {item.text} are present with both methods. So, why are the props for 'TodoItem' not being set when using 'forEach' ?
render() {
return(
<ul>
{this.props.items.forEach(function(item) {
return (
<TodoItem id={item.id} text={item.text} />)
})}
</ul>
);
}
因此,如果 'forEach' 没有返回任何内容,这也不起作用:
So if 'forEach' doesn't return anything how come this doesn't work either:
render() {
return(
<ul>
{this.props.items.forEach(function(item) {
<TodoItem id={item.id} text={item.text} />
})}
</ul>
);
}
推荐答案
map
函数返回一个项目数组,forEach
只是循环遍历它们.要使此代码工作,请使用:
The map
function returns an array of items and forEach
just loop over them. To make this code work use :
render() {
const items = [];
this.props.items
.forEach(item => items.push(
<li>
<TodoItem id={item.id} key={item.id} text={item.text} />
</li>
))
return(
<ul>{items}</ul>
);
}
这篇关于Reactjs 地图有效,但 forEach 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!