Reactjs地图工程,但forEach不 [英] Reactjs map works but forEach doesn't

查看:128
本文介绍了Reactjs地图工程,但forEach不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解forEach和map之间的区别。在下面的渲染函数中,如果'forEach'被替换为'map',它就会起作用。我不明白为什么它不适用于forEach。这两种方法都有{item.id}和{item.text}。那么,为什么在使用'forEach'的时候,'TodoItem'的道具没有被设置呢?

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆