我是一个本机反应的新手,试图找出哪里出了问题,但我找不到任何解决方案。我正在使用google日历api从日历中获取数据,我能够获取数据,但当我尝试解析并呈现它时,我会遇到这个错误。
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>
);
}
}发布于 2018-03-30 10:53:16
fetch和setState是异步的。当你渲染时,this.state.events将只是一个空数组,因为数据还不会被设置为更新。因此,当你在fetchData()的for循环中使用access it时,你会得到undefined,因为this.state.events将是你的[]的初始值。
另外,您的if语句:
if (this.state.events != null)由于this.state.events已初始化为[],因此不执行任何操作。它将始终执行,并且永远不会执行else语句中的操作。
我建议回顾一下异步代码在JavaScript中是如何工作的,因为它在React / React Native (fetch,setState等)中被大量使用。
https://stackoverflow.com/questions/49567705
复制相似问题