【问题标题】:Reactjs API Request IssueReactjs API 请求问题
【发布时间】:2019-11-06 03:15:54
【问题描述】:

我正在尝试从 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 给出:

【问题讨论】:

  • 能否请您显示控制台数据?
  • 好的,那么我认为你需要这样做:

    {games.results[0].name}

  • 它没有用。我收到此错误“TypeError: Cannot read property 'results' of undefined”

标签: reactjs axios


【解决方案1】:

您错误地映射了元素。

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>
);

编辑:当状态为空时,我必须处理这种情况。

希望对您有所帮助。干杯!!

【讨论】:

  • 在这一行

    {result.name}

  • 我在第一次回答后编辑了几次答案。你试过最后一个吗?
  • 我已经尝试了最后一个,我得到了这个错误“TypeError: Cannot read property 'forEach' of undefined”
  • 哦!我得到了它。等待
【解决方案2】:

你需要iterate over the object点赞,

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

【讨论】:

  • 怎么知道数据是不是对象?
  • @AdityaSrivast 作为 OP 尝试使用 games.name 访问数据,我想我们只对对象使用点(。)运算符。
猜你喜欢
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2016-12-03
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多