如何使用“ forEach”函数传递对象数组?

时间:2019-05-05 19:13:51

标签: javascript reactjs

我正在尝试创建在Card中创建的Card.js对象

 (const Card = (playerImage, name, position)) 

每个Card都是由在Players.js中创建的数据构建的。

Index.js文件中,我尝试使用forEach函数来传递数组中的每个索引并创建一个Card

消息错误是:

  

“玩家”未定义

(使用forEach可以变得更好,我知道这不是必需的)

谢谢:)

Players.js:

export const players = [
    {
        image = "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
        name = 'Keylor Navas',
        position = "GK"
    },
    {
        image = "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
        name = 'Sergio Ramos',
        position = "CB"
    }
]

Index.js:

ReactDOM.render((
    <div>
        players.forEach(player, index) => {
            <Card img = {player.image} name = {player.name} position = {player.position}/>
        });
    </div>),
    document.getElementById('root'));

5 个答案:

答案 0 :(得分:1)

尝试使用索引。

ReactDOM.render((
<div>
    {players.map((user, i) => {
        return ( 
           <Card 
                 key={i} 
                 img={players[i].image} 
                 name={players[i].name} 
                 position={players[i].position}
           /> 
        )
     });
    }
</div>),
document.getElementById('root'));

答案 1 :(得分:0)

您的代码中有错字

代替

players.forEach(player, index)

您的代码应为

players.forEach((player, index)

您缺少(

答案 2 :(得分:0)

您需要使用map而不是forEach

ReactDOM.render((
  <div>
    {players.map((player, index) => {
      return (
        <Card
          key={index} // if you objec has a Id field use it instead //of map index 
          img={player.img}
          name={player.name}
          position={player.position}
        />
      )
    });
    }
  </div>),
  document.getElementById('root'));

答案 3 :(得分:0)

您应该使用地图迭代器而不是foreach。 另外,请验证Players.js文件中的数据,该数据不是有效的JSON数据。该数据应为正确的JSON数据,否则您将收到错误。请参阅以下更正的数据。

export const players =[
    {
        image : "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
        name : 'Keylor Navas',
        position : "GK"
    },
    {
        image : "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
        name : 'Sergio Ramos',
        position : "CB"
    }
]

答案 4 :(得分:0)

# players.js
const players = [
  {
      image: "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
      name: 'Keylor Navas',
      position: "GK"
  },
  {
      image: "https://e00-marca.uecdn.es/assets/multimedia/imagenes/2019/01/09/15470342504519.jpg",
      name: 'Sergio Ramos',
      position:"CB"
  }
]
export players

# index.js
const myList = players.forEach( (player, index) => {
          <Card key={index} img={player.image} name={player.name} position={player.position}/>
      })

ReactDOM.render(<div>{myList}</div>, document.getElementById('root'));