React Native:访问 JSON 数据
React Native: Accessing JSON data
我正在使用 fetch
API 访问数据,事实证明,当访问我在数据源中设置的数据时,它 returns:
Warning: [TypeError: undefined is not an object(evaluating 'response.data.onwardflights')]
我确定我已经正确获取了数据,因为我已经通过将数据打印到控制台看到了数据。
这是相同的代码!
'use strict';
import React, {Component} from 'react';
import {StyleSheet, View, Text, ListView, ScrollView} from 'react-native';
const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
class BusList extends Component {
constructor() {
super();
// const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
this.state = {
dataSource: ds.cloneWithRows([]),
getData: []
};
}
componentDidMount() {
this.loadJSONData();
}
loadJSONData() {
fetch('api')
.then((response) => {
this.setState({getData: response})
this.setState({dataSource: ds.cloneWithRows(response.data.onwardflights)})
return response.json()
})
.then((responseJSON) => {
console.log(responseJSON)
return this.setState({dataSource: this.state.dataSource.cloneWithRows(responseJSON)});
})
.catch((error) => {
console.warn(error);
});
}
renderRow(rowData) {
return (
<View>
<Text>{rowData.origin}</Text>
</View>
);
}
render() {
return (
<View>
<ListView
dataSource = {this.state.dataSource}
enableEmptySections = {true}
renderRow = {(rowData) => <Text>{rowData}</Text>}
/>
</View>
);
}
}
module.exports = BusList;
任何帮助将不胜感激!
当然 response.data.onwardflights
将是 undefined
,因为您在读取数据之前没有调用 response.json()
。先调用方法,然后才读取数据。请阅读this article
我正在使用 fetch
API 访问数据,事实证明,当访问我在数据源中设置的数据时,它 returns:
Warning: [TypeError: undefined is not an object(evaluating 'response.data.onwardflights')]
我确定我已经正确获取了数据,因为我已经通过将数据打印到控制台看到了数据。
这是相同的代码!
'use strict';
import React, {Component} from 'react';
import {StyleSheet, View, Text, ListView, ScrollView} from 'react-native';
const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
class BusList extends Component {
constructor() {
super();
// const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});
this.state = {
dataSource: ds.cloneWithRows([]),
getData: []
};
}
componentDidMount() {
this.loadJSONData();
}
loadJSONData() {
fetch('api')
.then((response) => {
this.setState({getData: response})
this.setState({dataSource: ds.cloneWithRows(response.data.onwardflights)})
return response.json()
})
.then((responseJSON) => {
console.log(responseJSON)
return this.setState({dataSource: this.state.dataSource.cloneWithRows(responseJSON)});
})
.catch((error) => {
console.warn(error);
});
}
renderRow(rowData) {
return (
<View>
<Text>{rowData.origin}</Text>
</View>
);
}
render() {
return (
<View>
<ListView
dataSource = {this.state.dataSource}
enableEmptySections = {true}
renderRow = {(rowData) => <Text>{rowData}</Text>}
/>
</View>
);
}
}
module.exports = BusList;
任何帮助将不胜感激!
当然 response.data.onwardflights
将是 undefined
,因为您在读取数据之前没有调用 response.json()
。先调用方法,然后才读取数据。请阅读this article