首页 > 解决方案 > React - 从 API 获取数据并使用 MAP 函数返回显示

问题描述

我从 API 获得了一个 JSON,我正在尝试使用 MAP 函数在返回函数中显示这些数据。

但我得到了这个。

TypeError:this.state.callHistory.map 不是函数

也请帮助我处理total_calls

getCallHistoryList 函数工作正常,因为我在浏览器底座的网络选项卡中获取了数据。

主文件.js

import React, { Component } from 'react';
import axios from 'axios';

class Acallhistory extends Component {

  constructor(props) {
    super(props);
      this.state = {
        callHistory:[],
    };
  }   

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  componentDidMount(){
    this.getCallHistoryList();
  }

  getCallHistoryList() {
    const token = localStorage.getItem("AuthToken");
    const filterToken = token.replace(/['"]+/g, '');
    const payload = {
      from_date:'2021-05-17',
      to_date:'2021-05-07'
    }

    axios({
      method: 'post',
      url: 'https://APIURL',
      data: payload,
      headers: {
       'Content-Type': 'application/json',
       'Authorization': 'Bearer' + filterToken,
      }, 
    }).then((response) => {
        this.setState({ callHistory: response.data.data });
      })
      .catch((error) => {
        console.log(error)
      });
  };

  render() {
      return (
        <div>

             **<h5>Total calls: {this.state.callHistory.average_detail.total_calls} </h5>**  
        
                 <table class="table table-responsive">
                    <thead>
                      <tr>
                        <th>Interpreter</th>
                      </tr>
                    </thead>
                    <tbody>
                     {this.state.callHistory.map(member => 
                      <tr>
                        
                        <td>{member.call_datas.from_user_profile.first_name}</td>
                        
                      </tr>
                     )} 
                      
                    </tbody>
                 </table>
        </div>
      )    
  }
}

export default Acallhistory;

我的 JSON 看起来像这样-

{
    "status": true,
    "data": {
        "average_detail": {
            "total_calls": 6,
            "total_available_interpreter": 4,
            "avg_call_wait_time": "",
            "most_active_location": ""
        },
        "call_datas": [
            {
                "id": 6,
                "from_user_profile_id": 35,
                "from_user_role_id": 7,
                "purpose_id": 1,
                "language_id": 1,
                "action": 1,
                "status": {
                    "id": 10,
                    "name": "request",
                    "value": "Request"
                },
                "remarks": null,
                "is_recall": 0,
                "call_detail": "",
                "from_user_profile": {
                    "id": 35,
                    "user_id": 41,
                    "company_id": 2,
                    "first_name": "akshay",
                    "last_name": null,
                    "profile_photo": null,
                    "gender": null,
                    "date_of_join": null,
                    "date_of_birth": null,
                    "company": {
                        "id": 2,
                        "company_name": "AMAZON INDIA",
                        "company_type": 2,
                        "con_name": "ANKIT BOKARE",
                        "con_email": "ankitb.verve@gmail.com",
                        "company_address1": "Brigade Gateway, 8th floor, 26/1",
                        "company_address2": "Dr. Rajkumar Road, Malleshwaram(W)",
                        "company_city": "Bangalore",
                        "company_state": "Karnataka",
                        "company_country": "INDIA",
                        "company_zipcode": "560055",
                        "created_by": 1,
                        "updated_by": 1,
                        "deleted_at": null,
                        "created_at": "2021-04-21T05:16:49.000000Z",
                        "updated_at": "2021-04-21T05:16:49.000000Z"
                    },
                    "locations": {
                        "id": 34,
                        "user_profile_id": 35,
                        "city_id": 5,
                        "miles": "1",
                        "region": "1",
                        "site": "Gujrat",
                        "deleted_at": null,
                        "created_at": "2021-05-23T08:47:24.000000Z",
                        "updated_at": "2021-05-23T08:50:54.000000Z"
                    }
                }
            },
            {
                "id": 1,
                "from_user_profile_id": 35,
                "from_user_role_id": 7,
                "purpose_id": 1,
                "language_id": 2,
                "action": 1,
                "status": {
                    "id": 10,
                    "name": "request",
                    "value": "Request"
                },
                "remarks": null,
                "is_recall": 0,
                "call_detail": "",
                "from_user_profile": {
                    "id": 35,
                    "user_id": 41,
                    "company_id": 2,
                    "first_name": "akshay",
                    "last_name": null,
                    "profile_photo": null,
                    "gender": null,
                    "date_of_join": null,
                    "date_of_birth": null,
                    "company": {
                        "id": 2,
                        "company_name": "AMAZON INDIA",
                        "company_type": 2,
                        "con_name": "ANKIT BOKARE",
                        "con_email": "ankitb.verve@gmail.com",
                        "company_address1": "Brigade Gateway, 8th floor, 26/1",
                        "company_address2": "Dr. Rajkumar Road, Malleshwaram(W)",
                        "company_city": "Bangalore",
                        "company_state": "Karnataka",
                        "company_country": "INDIA",
                        "company_zipcode": "560055",
                        "created_by": 1,
                        "updated_by": 1,
                        "deleted_at": null,
                        "created_at": "2021-04-21T05:16:49.000000Z",
                        "updated_at": "2021-04-21T05:16:49.000000Z"
                    },
                    "locations": {
                        "id": 34,
                        "user_profile_id": 35,
                        "city_id": 5,
                        "miles": "1",
                        "region": "1",
                        "site": "Gujrat",
                        "deleted_at": null,
                        "created_at": "2021-05-23T08:47:24.000000Z",
                        "updated_at": "2021-05-23T08:50:54.000000Z"
                    }
                }
            }
        ]
    },
    "count": 6,
    "message": "translate.CALL_HISTORY_DATA",
    "totalNumberOfRecords": 6
}

标签: reactjsapimap-function

解决方案


componentDidMount在组件初始安装后调用。您的初始状态是一个空数组,因此在第一次渲染时 this.state.callHistory 将是一个空数组。挂载后,您将获得来自 axios 调用的响应,然后将其存储到状态中。

注意:您似乎正在将一个对象分配给一个数组的状态

then((response) => {
        this.setState({ callHistory: response.data.data });
 })

我想这就是你想要做的

then((response) => {
        this.setState({ callHistory: [response.data.data] });
 })


只需修改您的渲染方法以包含条件检查。仅当 this.state.callHistory 的长度大于 0 时才渲染。


<div>

    {this.state.callHistory.length > 0 &&

             **<h5>Total calls: {this.state.callHistory.average_detail.total_calls} </h5>**  
        
                 <table class="table table-responsive">
                    <thead>
                      <tr>
                        <th>Interpreter</th>
                      </tr>
                    </thead>
                    <tbody>
                     {this.state.callHistory.map(member => 
                      <tr>
                        
                        <td>{member.call_datas.from_user_profile.first_name}</td>
                        
                      </tr>
                     )} 
                      
                    </tbody>
                 </table>
      }
</div>


仅当数组包含响应数据时才会呈现。您当然可以使用三元运算符修改条件以具有 if else 条件。


推荐阅读