如何遍历`this.state`对象中的数组?

时间:2019-04-02 12:51:06

标签: javascript reactjs

我有一个GET请求正在提取数据,该数据包含一个object,然后在array中包含一个object。然后,我使用this.setState,现在在arrayobject

中有一个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>
        )
    }
}

最后,我试图遍历从端点接收的数据并遍历每个索引并显示其属性。

更新const game = res.data的问题在于,因为这是一个对象,所以导致对象中的对象出现问题。将其更改为res.data.games可以解决此问题,因为.games是给定数据中的数组。

3 个答案:

答案 0 :(得分:1)

您试图遍历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) {

答案 1 :(得分: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>
    )
}

直到从服务器加载数据的时间,您可以显示一些动画 而不是简单的消息,

答案 2 :(得分:0)

更改

        this.state.games.games.forEach(function (game, index) {

        })

        this.state.games.forEach(function (game, index){

        })