我正在尝试从Zomato API(https://developers.zomato.com/documentation)获取集合,并且试图检索集合列表并将其显示在flatList上。但是,每次尝试检索它时,我的终端似乎都会输出undefined
这是我的代码
async componentDidMount(){
try {
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
});
this.setState({ data: res.data });
console.log(res.data.collections.title)
} catch (err) {
console.log(err);
} finally {
this.setState({ isLoading: false });
}
};
当我console.log(res.data.collections)
时,我从API获得集合数组中所有组件的完整列表。但是,当我尝试访问标题组件时;终端输出undefined
我在做什么错了?
答案 0 :(得分:1)
请检查以下代码,我认为您的代码有一个小问题,您未提取确切的数据。香港专业教育学院通过显示餐厅的标题来纠正它。您可以做更多。博览会链接为expo-link
import React from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
TouchableHighlight,
Dimensions,
Image,
} from 'react-native';
import Modal from 'react-native-modal';
import { createAppContainer } from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { Card, Icon, Button } from 'react-native-elements';
import Constants from 'expo-constants';
// import {apiCall} from '../src/api/Zomato';
// import Logo from '../assets/Logo.png';
import axios from 'axios';
export default class HomeScreen extends React.Component {
constructor(props){
super(props);
// this.navigate = this.props.navigation.navigate;
this.state={
data : [],
isModalVisible: false,
loca: 280
}
}
async componentDidMount(){
try {
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
});
// alert(res.data.collections, 'response');
this.setState({ data: res.data.collections });
} catch (err) {
console.log(err);
} finally {
}
}
render() {
return (
<View>
<FlatList
style={{marginBottom: 80}}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> this.props.navigation.navigate('CategoryScreen', { category: item.categories.id, city: this.state.loca })}>
<Card>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.collection.title} </Text>
</Card>
</TouchableHighlight>}
/>
</View>
);
}
}
如有任何疑问,请还原,不明确。希望能有所帮助;
答案 1 :(得分:0)
Axios返回一个承诺,尝试将setState保留在.then
中,并停止信任console.log
axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
}).then( res => this.setState({res}))