Api undefined不是对象(正在计算'this.state.events[i].summary')
我是一个新手,会做出本地反应,并试图找出这里的问题所在,但我找不到任何解决方案。我使用GoogleCalendarAPI从日历中获取数据,我能够获取数据,但是当我试图解析并呈现它时,我会遇到这个错误Api undefined不是对象(正在计算'this.state.events[i].summary'),api,react-native,google-calendar-api,fetch,Api,React Native,Google Calendar Api,Fetch,我是一个新手,会做出本地反应,并试图找出这里的问题所在,但我找不到任何解决方案。我使用GoogleCalendarAPI从日历中获取数据,我能够获取数据,但是当我试图解析并呈现它时,我会遇到这个错误 import React from 'react'; import { SafeAreaView, View, Text, StatusBar, Image, AppRegistry, ScrollView, StyleSheet, TouchableHighlight, FlatList } fr
import React from 'react';
import { SafeAreaView, View, Text, StatusBar, Image, AppRegistry, ScrollView, StyleSheet, TouchableHighlight, FlatList } from 'react-native';
import glamorous from "glamorous-native";
import { Calendar, Agenda } from 'react-native-calendars';
import { bColor, pColor } from "../style/colors"
import request from 'superagent'
import PostItem from "../elements/PostItem"
export default class AppCalendar extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: "Calendar",
});
componentWillMount() {
this.setState({
events:[]
})
}
componentDidMount(){
let postsUrl = "https://www.googleapis.com/calendar/v3/calendars/calendarId/apiKey
fetch(postsUrl)
.then((response) => response.json())
.then((response) => {
this.setState({
events: response
})
})
}
fetchData(){
let e = []
if (this.state.events != null) {
for (let i = 0; i < 3; i++) {
let newEvent = {}
newEvent.title = this.state.events[i].summary
newEvent.location = this.state.events[i].location
newEvent.startDate = this.state.events[i].start.date || this.state.events[i].start.dateTime
newEvent.endDate = this.state.events[i].end.date || this.state.events[i].end.dateTime
if(newEvent.startDate)
e.push(newEvent)
}
return e
}
else {
return 'yanlis'
}
}
render() {
console.log('length is', this.state.events.length)
return (
<View>
<Text>{this.fetchData()}</Text>
</View>
);
}
}
fetch和setState是异步的。渲染时,this.state.events将只是一个空数组,因为数据尚未设置为更新。因此,当您在fetchData的for循环中使用access时,您将无法定义this.state.events,因为它只是您的初始值[]
此外,您的if声明:
if (this.state.events != null)
自this.state.events初始化为[]后,不执行任何操作。它将始终执行,并且永远不会执行else语句中的操作
我建议回顾一下异步代码在JavaScript中的工作原理,因为它在React/React Native fetch、setState等中大量使用。我查看了它,有点困惑。当代码启动时,componentDidmount将工作,事件将从api中填充,但我猜这将在获取数据之后发生。因此,事件将为空。我怎样才能让它在componentDidMount之后像fetchData那样工作?我把fetch放在组件did mount中是不是做错了,因为它将被渲染激活@迈克尔Cheng@uguryiilmz如果您检查数组的长度,而不是它是否为null,并且如果您将this.state.events控件移动到从fetchData渲染,它将修复您的问题。{this.state.events.length>0&&{this.fetchData}我已经完成了,现在我得到了一个空白页,我不知道为什么。我试图在接口中显示所有json数据,但它只是一个空白页面,即使数组中填充了@bennygenel的数据