首页 > 解决方案 > 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;

标签: javascriptreactjsapiaxios

解决方案


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

推荐阅读