javascript Reactjs 地图有效,但 forEach 无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47442462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reactjs map works but forEach doesn't
提问by DCR
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' ?
我正在努力理解 forEach 和 map 之间的区别。在下面的渲染函数中,如果 'forEach' 被替换为 'map',它就可以工作。我不明白为什么它不适用于“forEach”。{item.id} 和 {item.text} 都存在于这两种方法中。那么,为什么在使用 'forEach' 时没有设置 'TodoItem' 的道具?
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:
因此,如果 'forEach' 没有返回任何内容,这也不起作用:
render() {
return(
<ul>
{this.props.items.forEach(function(item) {
<TodoItem id={item.id} text={item.text} />
})}
</ul>
);
}
回答by Ajay Gaur
The mapfunction returns an array of items and forEachjust loop over them. To make this code work use :
该map函数返回一个项目数组,然后forEach循环遍历它们。要使此代码工作,请使用:
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>
);
}
回答by Gonzalo Pincheira Arancibia
Try this simple example for understand why forEach doesn't work in this context:
试试这个简单的例子来理解为什么 forEach 在这种情况下不起作用:
[1,2,3].forEach((n)=> n); => returns undefined
[1,2,3].map((n)=> n); => returns [1,2,3]
回答by maioman
Basically mapreturns an array while forEachreturns nothing,
基本上map返回一个数组而forEach什么都不返回,
in jsx/react contextyou need to return a list of components/node-tags that the parser will transform in nodes both in the real and virtual dom;
在jsx/react 上下文中,您需要返回解析器将在真实和虚拟 dom 中的节点中转换的组件/节点标签列表;
working by side-effect like forEach does you won't have anything to parse.
通过像 forEach 这样的副作用工作,您将没有任何要解析的内容。
回答by redhedjim
As @Nenad Vracar mentioned mapwill actually return stuff. If you wanted to do somethings to another array, object or piece of code you could use forEach. But since you want to return something that ends up being shown on the DOM. Use map.
正如@Nenad Vracar 提到的,map实际上会返回东西。如果你想对另一个数组、对象或一段代码做一些事情,你可以使用forEach. 但是因为你想返回一些最终显示在 DOM 上的东西。使用map.
Also, don't forget to returnwhatever you're mapping. It's a common mistake because you don't need to use the return for forEach.
另外,不要忘记return您正在映射的任何内容。这是一个常见的错误,因为您不需要使用 return for forEach。

