3 回答

TA贡献1752条经验 获得超4个赞
你试图通过环this.state.games.games,但在你的构造,初值你给state的{ games: [] }。因此,this.state.games.games最初不是数组,这就是为什么出现错误的原因。
两种修复方法。
将状态初始化为一个反映您访问状态的结构:
this.state = { games: { games: [] } };
或者,可能是一个更好的主意,更改您的代码,以使您的数组this.state.games而不是this.state.games.games:
.then(res => {
const games = res.data.games;
this.setState({ games })
})
// further below ...
this.state.games.forEach(function (game, index) {

TA贡献1772条经验 获得超6个赞
改变
this.state.games.games.forEach(function (game, index) {
})
至
this.state.games.forEach(function (game, index){
})

TA贡献1111条经验 获得超0个赞
您正在进行ajax调用,这是异步的,您尝试在ajax调用完成之前使用状态的游戏,因此导致错误
//your render method
render() {
const games = [];
if(this.state.games.games.length<=0){
return <h1>Please wait while loading data</h1>
}
try {
this.state.games.games.forEach(function (game, index) {
console.log(index) // index
console.log(game) // value
games.push(
<Grid.Column>
<MyGames key={index} game={{title: game.title, description: game.genre, thumbnail: game.thumbnail}}/>
</Grid.Column>
)
})
}
catch( e ) {
console.log("Error: " + e );
}
return (
<div>
<Grid columns={1}>
<Grid.Column>
<FriendsList/>
<Header as='h3'>My Games</Header>
<Grid columns={4} container={'true'} padded>
{games}
</Grid>
</Grid.Column>
</Grid>
</div>
)
}
直到从服务器加载数据之前,您可以显示一些动画而不是普通消息,
添加回答
举报