Reactjs地图工程,但forEach不 [英] Reactjs map works but forEach doesn't
本文介绍了Reactjs地图工程,但forEach不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
render(){$ b $ (
< ul>
{this.props.items.forEach(function(item)){
return(
< TodoItem id = {item.id} text = {item.text} />)
})}
< / ul>
);
$ b因此如果'forEach'不返回任何东西, (
$ lt; ul> $
{this.props.items.forEach(function(item){
< TodoItem id = {item.id} text = {item.text} />
} )}
< / ul>
);
解决方案
map
函数返回一个数组项, forEach
只是循环它们。为了使这段代码有效: render(){
const items = [];
this.props.items.forEach(item => items.push(
< li>
< TodoItem id = {item.id} key = {item.id} text = {item.text} />
< / li>
))
返回(
< ul>
{items}
< / ul>
);
}
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>
);
}
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>
);
}
解决方案
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屋!
查看全文