【问题标题】:Why can't I display the contents of this API?为什么我无法显示此 API 的内容?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 知道了!非常感谢。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2017-07-11
      • 2013-01-06
      • 2021-04-08
      相关资源
      最近更新 更多