为什么我不能显示此API的内容?

时间:2018-07-08 19:26:21

标签: javascript reactjs api axios

我正在尝试显示此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;

2 个答案:

答案 0 :(得分:2)

您的初始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 });
       });
   }
  // ...
}

答案 1 :(得分:0)

由于响应是一个json对象,因此您必须首先使用JSON.parse()解析它