Reactjs API请求问题

时间:2019-06-24 10:18:50

标签: reactjs axios

我正在尝试从GameSpot API获取一些数据并显示它们。我可以在控制台中看到这些数据,但不能在我的网页上看到它们。

import React, { Component } from 'react';
import axios from 'axios';


class Games extends Component {
    constructor(){
        super();
        this.state={
          games: [],
        }
    }

    componentDidMount() {
        axios.get(`http://www.gamespot.com/api/games/?api_key=[APIKEY]&format=json&filter=name:Cyberpunk 2077,limit:10`)          
            .then(res => {
                this.setState({
                    games: res.data
                })
            })
            .catch(error=>{
                console.log(error);
            })


    }
    render() {
        const {games} = this.state;
        console.log(games);

        return (
            <div>
              <p>{games.name}</p>
            </div>

        );
    }
}

我希望在我的网页上看到结果数据

编辑: console.log 提供:

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要iterate over the object喜欢

Object.keys(games.name).forEach(function(key) {
    <p>{games.name[key]}</p>
});

答案 1 :(得分:0)

您错误地映射了元素。

render函数中尝试:

const {results} = this.state.games;
let names =[];
if(results && results.length) {
  results.forEach(result=> {
    names.push(<p>{result.name}</p>);
  });
}
return (
  <div>
    {names}
  </div>
);

编辑:状态为null时,我不得不处理这种情况。

希望有帮助。干杯!