我有一个GET提取数据的请求,数据中包含object,然后包含array中的object。然后,我使用this.setState,现在array在object中有一个object
问题是,当我尝试遍历数组时,我不能,因为我得到了一个
TypeError: this.state.games.games is undefined
如果我只有this.state.games,并尝试遍历,我会得到一个
TypeError: this.state.games.forEach is not a function
我已经通过一种try...catch方法解决了这个问题,但是我认为这不是解决此问题的最佳方法。
class HomePage extends Component {
constructor(props) {
super(props)
this.state = {games: []}
}
componentDidMount() {
axios.get(`http://localhost.com:5000/user/games`, {withCredentials: true})
.then(res => {
const games = res.data;
this.setState({ games })
})
}
render() {
const games = [];
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>
)
}
}
最后,我试图遍历从端点接收的数据并遍历每个索引并显示其属性。
温温酱
梦里花落0921
catspeake
相关分类