访问函数中的 fetch() 数据

Accessing fetch() data that lives in a function

我正在尝试学习 React 并尝试为我的网站制作一个链接到 public Google 日历的日历。我花了很长时间才弄清楚如何获得我需要的信息,但我做到了。现在,我遇到了一个问题,它更面向香草 Javascript...

我的代码如下所示:

import React, { Component } from 'react';

export default class Calendar extends Component {
    async getEventNames() {
        try {
            await fetch('https://clients6.google.com/calendar/v3/calendars/b2f8g8daabnmpqo43v04s6fl3g@group.calendar.google.com/events?calendarId=b2f8g8daabnmpqo43v04s6fl3g%40group.calendar.google.com&singleEvents=true&timeZone=Europe%2FAmsterdam&maxAttendees=1&maxResults=250&sanitizeHtml=false&timeMin=2019-04-01T00%3A00%3A00%2B02%3A00&timeMax=2019-05-06T00%3A00%3A00%2B02%3A00&key=AIzaSyBNlYH01_9Hc5S1J9vuFmu2nUqBZJNAXxs')
                .then(res => {
                    return res.json();
                })
                .then(data => {
                    const nameArr = data.items.map(item => {
                        return item.summary;
                    });
                    console.log(nameArr);
                    return nameArr;
                });
        } catch (err) {
            console.error(err);
        }
    }
    render() {
        const arr = this.getEventNames();
        console.log(arr);
        return <div />;
    }
}

因此,我从我的日历中获取数据,将其转换为 JSON 数组,将其映射到数组中并 return 它。或者至少这就是我想要的...... 注意那里有两个 console.log()getEventNames() 函数中的那个给出了我想要的数组,但是 render() 函数中的那个给了我 "Promise {pending}".

我对 Promises 一无所知,并且准备接受有关它们的培训,但也有人可以教我如何从我的函数中获取数组吗?

拜托,谢谢,祝你复活节愉快(或你的文化中的春假):)

最常使用 state 和 componentDidMount,因为它是 "load data from a remote endpoint."

的最佳位置
import React, { Component } from 'react';

export default class Calendar extends Component {
  constructor(props) {
   super(props);

    this.state = {
      eventNames: []
    }
  }

  componentDidMount() {
    fetch('...')
     .then(res => {
       res.json().then(eventNames => {
         this.setState({eventNames});
       });
    }).catch(err => {
     // Error handling
    })
  }

  render() {
      console.log(this.state.eventNames);
      return <div />;
  }
}

我也同意评论中所说的一切,所以请记住这些:)

https://reactjs.org/docs/react-component.html#componentdidmount