javascript - Why can't I display the contents of this API?
问题描述
I'm trying to display the contents of this API http://lookup-service-prod.mlb.com/json/named.psc_leader_hit_hr_dist.bam?season=2015&game_type=%27D%27&game_type=%27L%27&game_type%27W%27&game_type=%27F%27&min_hip_count=15 but I keep getting an error that says:
TypeError: this.state.persons.map is not a function
20 | render() {
21 | return (
22 | <ul>
> 23 | {this.state.persons.map(person => <li>{person.result}</li>)}
24 | </ul>
25 |
26 | );
This code below is the code to try to display the contents of the API. I know the API starts out with {}
but in state = {persons: []
I used []
. This won't work out because this API starts with curly brackets. How can I make it so that that I can use {}
(curly brackets) successfully with map()
function in order to display contents of this API? What am I doing wrong?
Here's Data.js
:
import React, {Component} from 'react';
import axios from 'axios';
class Data extends Component {
state = {
persons: []
}
componentDidMount() {
axios.get('http://lookup-service-prod.mlb.com/json/named.psc_leader_hit_hr_dist.bam?season=2015&game_type=%27D%27&game_type=%27L%27&game_type%27W%27&game_type=%27F%27&min_hip_count=15')
.then(res => {
this.setState({persons: res.data});
console.log(res);
});
}
render() {
return (
<ul>
{this.state.persons.map(person => <li>{person.result}</li>)}
</ul>
);
}
}
export default Data;
解决方案
您的初始persons
状态是一个对象,而对象没有map
方法。而是将其默认为数组。
您还需要访问响应中的数组res.data.psc_leader_hit_hr_dist.queryResults.row
:
class Data extends Component {
state = {
persons: []
}
componentDidMount() {
axios.get('http://lookup-service-prod.mlb.com/json/named.psc_leader_hit_hr_dist.bam?season=2015&game_type=%27D%27&game_type=%27L%27&game_type%27W%27&game_type=%27F%27&min_hip_count=15')
.then(res => {
this.setState({ persons: res.data.psc_leader_hit_hr_dist.queryResults.row });
});
}
// ...
}
推荐阅读
- flutter - 在 dart 中,如何删除 NestedList 中的元素
- node.js - docker和节点的Nginx 504超时
- javascript - 如何将网页上播放的音频用作网络语音 API 的输入?
- php - Laravel 路由参数除了
- julia - 如何在 Julia 中创建列表?
- c++ - c++ - 初始化列表时如何释放资源引发异常?
- html - 如何在 Ant 设计中为下拉菜单编写自定义 CSS
- android - 片段 setOnTouchListener 未触发
- xml - 使用 xsl translate 替换右引号字符
- swift - 架构 arm64 的 1 个重复符号