首页 > 解决方案 > React Axios - JSON Get 响应未从 render() 显示 - Riot API

问题描述

几天前我开始学习 React,今天开始学习 Axios。在过去的 4 个多小时里,我一直在观看/阅读教程,但我无法弄清楚这一点。

我正在尝试使用Riot 的 API为英雄联盟创建一个简单的统计网站。您可以在下面看到我的构造函数、componentDidMount 和渲染函数。我觉得我做错了 3 个中的 1 个,或者很可能是全部 3 个。我称之为Get,它返回下面的 JSON。我想访问“name”和“accountId”。

{
  "profileIconId": 3270,
  "name": "Doublelift",
  "puuid": "SrvIz_3Xa05InF_hTjwq1v8iB6lqNXz0SEc_5vhOFYlScrZOg8pSM9Si_UdPGAD9UYGhaRWHBeBGrw",
  "summonerLevel": 155,
  "accountId": "iNc_SUPKq-ckcANeC36Yn18Y0XSofK3ShBQg_h5wivC0Bg",
  "id": "DjnxZhsTjgNhv3sMZMMJjlCUqAskiMfP6bP7GIcWovbwR1k",
  "revisionDate": 1580499454000
}

我应该注意我将我的 API 密钥设为默认值。它存储在我的 index.js 文件中。这安全吗?

axios.defaults.headers.common['Authentication'] = 'API-Key-randomlettersandnumbers';

这是我的代码。在 render() 中,当我键入时summonerDetail.[field],它会识别上面 JSON 响应中显示的字段。也许我的渲染错误导致它不显示?是的,我知道“accountID”不在我的渲染中。我想我会从“名字”开始。我最终将需要为不同的 Get 使用“accountID”。

    import React from 'react';
    import axios from 'axios';

    export default class GetBySummonerName extends React.Component {

      constructor(props){
        super(props);
        this.state = {
          summonerDetails: []
        };
      }

      // https request to perform Get
      componentDidMount() {
        axios.get('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/doublelift')
          .then(res => {
            console.log(res);
            this.setState({ summonerDetails: res.data});
          })
      }

      render() {
        return (
            <div>
              { this.state.summonerDetails.map(summonerDetail => <h1>{summonerDetail.name}</h1>)}
            </div>
        )
      }
    }

为了在网站上显示“名称”,我将上述类导入 App.js。唯一的问题是它不起作用。我有 console.log(res); 在我的 ComponentDidMount() 中,但我不知道如何在 Atom 中查看控制台。我的 componentDidMount() 中不需要任何标题,因为“summonerName”在 Get URL 中。其余的标题是在 Riot 方面自动生成的。请帮忙 :)

标签: javascriptreactjsapiaxiosriot-games-api

解决方案


你不需要map。如果您收到如下对象res.data

{
    "profileIconId": 3270,
    "name": "Doublelift",
    "puuid": "SrvIz_3Xa05InF_hTjwq1v8iB6lqNXz0SEc_5vhOFYlScrZOg8pSM9Si_UdPGAD9UYGhaRWHBeBGrw",
    "summonerLevel": 155,
    "accountId": "iNc_SUPKq-ckcANeC36Yn18Y0XSofK3ShBQg_h5wivC0Bg",
    "id": "DjnxZhsTjgNhv3sMZMMJjlCUqAskiMfP6bP7GIcWovbwR1k",
    "revisionDate": 1580499454000
}

然后在你的 return 语句中替换它。

<div>{ this.state.summonerDetails.name }</div>

希望这对你有用。


推荐阅读