繁体   English   中英

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

[英]How do I loop though an array in a `this.state` object?

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

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

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

您正在尝试遍历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) {

您正在进行 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>
    )
}

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

改变

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

        })

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

        })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM