【发布时间】:2018-12-16 12:49:00
【问题描述】:
我正在尝试显示此 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 的内容,但我不断收到一条错误消息:
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 | );
下面的这段代码是尝试显示 API 内容的代码。我知道 API 以 {} 开头,但在 state = {persons: [] 中我使用了 []。这是行不通的,因为这个 API 以大括号开头。我怎样才能使我可以成功地使用{}(大括号)和map()函数来显示这个API的内容?我做错了什么?
这里是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;
【问题讨论】:
标签: javascript reactjs api axios