我有一个 GET
请求获取数据,数据包含一个 object
然后是 object
中的一个 array
>。然后,我使用 this.setState
,现在有一个 array
,在 object
中,在 object
/p>
问题是,当我尝试遍历数组时,我不能,因为我得到了一个
类型错误:this.state.games.games 未定义
如果我只有 this.state.games
,并尝试循环我得到一个
类型错误:this.state.games.forEach 不是函数
我已经通过 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>
)
}
}
最后,我试图循环遍历从端点接收的数据并循环遍历每个索引并显示它们的属性。
更新:
问题出在 const game = res.data
上,因为这是一个对象,它导致对象中的对象出现问题。将其更改为 res.data.games
解决了问题,因为 .games
是给定数据中的数组。
最佳答案
您正在尝试遍历 this.state.games.games
,但是在您的构造函数中,您赋予 state
的初始值是 { games : []
。因此,this.state.games.games
最初不是数组,这就是您收到错误的原因。
两种修复方法。
将您的状态初始化为反射(reflect)您访问状态的方式的结构:
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) {
关于javascript - 如何循环遍历 `this.state` 对象中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55475261/