我几天前开始学习 React,今天开始学习 Axios。我花了过去 4 个多小时观看/阅读教程,但我就是不明白这一点。
我正在尝试使用Riot's API为英雄联盟创建一个简单的统计网站。 。下面你可以看到我的构造函数、componentDidMount 和渲染函数。我觉得我做错了 3 个中的 1 个,或者很可能全部 3 个都错了。我正在调用 this 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 key 设置为默认值。它存储在我的 index.js 文件中。这安全吗?
axios.defaults.headers.common['Authentication'] = 'API-Key-randomlettersandnumbers';
这是我的代码。在 render() 中,当我输入 summonerDetail.[field]
时,它会识别上面 JSON 响应中显示的字段。也许我的渲染错误导致它无法显示?是的,我知道“accountID”不在我的渲染中。我想我应该从“名字”开始。我最终需要将“accountID”用于不同的 Get。
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() 中不需要任何 header ,因为“summonerName”位于 Get URL 中。其余 header 由 Riot 自动生成。请帮忙:)
最佳答案
您不需要映射
。如果您在 res.data
{
"profileIconId": 3270,
"name": "Doublelift",
"puuid": "SrvIz_3Xa05InF_hTjwq1v8iB6lqNXz0SEc_5vhOFYlScrZOg8pSM9Si_UdPGAD9UYGhaRWHBeBGrw",
"summonerLevel": 155,
"accountId": "iNc_SUPKq-ckcANeC36Yn18Y0XSofK3ShBQg_h5wivC0Bg",
"id": "DjnxZhsTjgNhv3sMZMMJjlCUqAskiMfP6bP7GIcWovbwR1k",
"revisionDate": 1580499454000
}
然后在返回语句中替换它。
<div>{ this.state.summonerDetails.name }</div>
希望这对您有用。
关于javascript - React Axios - JSON Get 响应未从 render() 显示 - Riot API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60052866/