编码问题,无法用 API 个元素组成数组,Reactjs

Coding problem, can't make array out of API elements, Reactjs

好的,这是我第一次 post 在 Whosebug 上,所以基本上我是 JS、React、Web Dev 的新手,我无法用 post 中的一些数据制作数组=28=] API.

的响应

为此我遵循了许多类似的教程,但我似乎无法正确理解,也许我在路径上犯了错误。

这是JSON的一部分:

meta: {code: 200}
   response:
    holidays: Array(34)
           0:
            date:
             datetime: {year: 2019, month: 1, day: 1}
             iso: "2019-01-01"
__proto__: Object
description: "New Year’s Day (Anul Nou) and the following day, on January 1 and 2 respectively, are annual holidays in Romania."
locations: "All"
name: "New Year's Day"
states: "All"
type: ["National holiday"]
__proto__: Object
           1: {name: "Day after New Year's Day", description: "Both New Year’s Day (Anul Nou) and the following d…d 2 respectively, are annual holidays in Romania.", date: {…}, type: Array(1), locations: "All", …}
           2: {name: "Unification Day", description: "Unification Day celebrates the political union bet…ch is deemed as the foundation of modern Romania.", date: {…}, type: Array(1), locations: "All", …}

这就是我尝试使用 componentDidMount 访问 API 的方式:

componentDidMount() {

   const endpoint = 'https://calendarific.com/api/v2/holidays?api_key=065cc39ad5c1967ae719985ce3850f264f0215b7015d801b098df1ca9fca725b&country=RO&year=2019';
   fetch(endpoint)
   .then(results => results.json())
 }

这就是我尝试制作一个函数的方法,该函数采用数组中所有元素的年月日,return另一个数组仅包含所有日期:

 holidayDateArray(data){
   let holidayDates= data;
   let holidays= holidayDates.response.holidays;
   let holidaysArray= holidays.map((items, i)=>{
     return {items.date.datetime.year}+" "+{items.date.datetime.month}+" "+{items.date.datetime.day}
   });
 }

基本上我希望 holidayDateArray 函数 return 一个由假期数组中所有元素的日期组成的数组。

试试这个

   fetch(endpoint)
   .then(results => results.json()).then(r => console.log($.map(r.response.holidays, h => h.date)))

results.json() 将 return 一个承诺,因为当反序列化完成时,所以你也必须等待它。之后,您可以使用 $.map 和 return 遍历数组中的所有元素返回基于 属性 date

的数组

import React, {
  Component
} from "react";

class MyComponent extends Component {
  componentDidMount() {
    const endpoint = 'https://calendarific.com/api/v2/holidays?api_key=065cc39ad5c1967ae719985ce3850f264f0215b7015d801b098df1ca9fca725b&country=RO&year=2019';

    fetch(endpoint)
      .then(response => response.json())
      .then(myJson => {
        const listOfDates = this.getListOfDates(myJson);
        //set listOfDates to a state variable / instance variable and use as necessary
        console.log(listOfDates);
      });
  }

  getListOfDates(myJson) {
    const holidayLists = myJson.response.holidays;
    const dateList = holidayLists.map(holidayListItem => {
      const dateTime = holidayListItem.date.datetime;
      // return dateTime.iso; 
      return `${dateTime.year} ${dateTime.month} ${dateTime.day}`;
    });
    return dateList;
  }
}