使用 React Native 从 API 获取数据
Fetch data from API using React Native
我正在尝试从下面的 url 中获取数据,但是当我启动代码时 returns 出现错误:TypeError: undefined is not an object (evaluating 'res.data.hints')
,因此没有任何反应,我已经按照各种教程,他们似乎想出了这段代码。
州
constructor(props) {
super(props);
this.updateSearch();
this.state = {
data: [],
};
}
函数
updateSearch = () => {
const url = `https://api.edamam.com/api/food-database/v2/parser?ingr=b&app_id=000&app_key=00000&page=20`;
fetch(url)
.then((res) => res.json())
.then((res) => {
this.setState({
data: res.data.hints
});
})
.catch(error => {
console.log("error : "+ error)
});
};
Flatlist
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem>
<TouchableOpacity>
<View>
<Text>{item.label}</Text>
<Text>{item.brand}</Text>
</View>
</TouchableOpacity>
</ListItem>
)}
keyExtractor={(item) => item.foodId}
/>
this.setState({
data: res.hints
});
试试这个
我正在尝试从下面的 url 中获取数据,但是当我启动代码时 returns 出现错误:TypeError: undefined is not an object (evaluating 'res.data.hints')
,因此没有任何反应,我已经按照各种教程,他们似乎想出了这段代码。
州
constructor(props) {
super(props);
this.updateSearch();
this.state = {
data: [],
};
}
函数
updateSearch = () => {
const url = `https://api.edamam.com/api/food-database/v2/parser?ingr=b&app_id=000&app_key=00000&page=20`;
fetch(url)
.then((res) => res.json())
.then((res) => {
this.setState({
data: res.data.hints
});
})
.catch(error => {
console.log("error : "+ error)
});
};
Flatlist
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<ListItem>
<TouchableOpacity>
<View>
<Text>{item.label}</Text>
<Text>{item.brand}</Text>
</View>
</TouchableOpacity>
</ListItem>
)}
keyExtractor={(item) => item.foodId}
/>
this.setState({
data: res.hints
});
试试这个