我在将对象推入数组时遇到问题。我正在从本地.json文件中提取对象数组。我正在尝试创建一个将给定对象推送到数组中的函数,因此以后可以使用它。
这就是我收到物品的方式。
{id: 3176, name: "Matthias Ginter", position: "Defender", dateOfBirth: "1994-01-03T00:00:00Z", countryOfBirth: "Germany", …}
countryOfBirth: "Germany"
dateOfBirth: "1994-01-03T00:00:00Z"
id: 3176
name: "Matthias Ginter"
nationality: "Germany"
position: "Defender"
role: "PLAYER"
__proto__: Object
我在React中的代码:
{data.map(
(player) => (
player.position == null ? (player.position = "Coach") : null,
(
<PlayerCard
name={player.name}
position={player.position}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)
)}
以及我要插入的数组:
let selectedPlayers = [
{
id: 3176,
name: "Matthias Ginter",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
{
id: 3176,
name: "Mat Giensien",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
];
如果我做handleClick = {() => {console.log(player)}}
,则会得到如上所示的对象。我想念什么?!
我已经阅读了SO中的所有主题,但是找不到适合我的解决方案。我在其他主题中尝试了所有推荐的方法,但它们仍然对我不起作用。
请,请暂停:)
答案 0 :(得分:0)
{data.map(player => {
return (
<PlayerCard
name={player.name}
position={player.position ? "Coach" : null}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)}