使用 .map() 在对象 React 中迭代数组

Qu4*_*4k3 1 javascript reactjs axios array.prototype.map

我试图迭代对象数组中的 throw 元素,但由于返回的数据不是数组而是对象,因此 .map() 不能以简单的方式使用。

API 返回以下结构

/玩家(端点)

{
  "players": [
    {
      "player_id": "Uy2sZ5ef",
      "player_name": "Foo",
      "player_team": "5c50bae023213348c4453aaf"      
    },
    {      
      "player_id": "h15sqI4D",
      "player_name": "Foo 2",
      "player_team": "5c50bae023213348c4453aaf"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

反应组件

export class Players extends Component {
    state = {
        players: []
    }

    componentDidMount() {
    API.get(`players/`).then(res => {
            console.log(res)
            this.setState({ players: res.data })
        })
    }

    render() {
        return (
            <section className="contents">

                { this.state.players.map(player => <li>{player.player_name}</li>)}

            </section>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台错误

Cev*_*mic 7

如果你的数据看起来像那个对象,而你只需要玩家,你应该:

    componentDidMount() {
    API.get(`players/`).then(res => {
            console.log(res)
            this.setState({ players: res.data.players }) // <-- get only the players
        })
    }
Run Code Online (Sandbox Code Playgroud)