下面的代码在控制台中打印响应,但是当使用useState的useState方法将其更新到结果时,它不起作用。在我的JSX代码中,它没有输出任何替代result.length的内容。
import React, { useState } from 'react';
import {Text, View, StyleSheet,Button } from 'react-native'
import axios from 'axios'
const WeatherAPI = () => {
const [ results, setResults] = useState([]);
const getAPIresults = async () => {
await axios.get("https://newsapi.org/v2/top-headlines?country=us&apiKey=<mykeyhere>")
.then((response)=>{
console.log(response);
setResults(response);
})
.catch((error)=>{
console.log(error)
})
}
return(
<View>
<Text> We got {results.length} items</Text>
<Button title="GetAPI" onPress = {() => {getAPIresults()}} />
</View>
)
}我将空数组初始化为结果,但响应将是一个对象。因此,我尝试分配一个数组而不是一个对象。React并不重要,但我尝试更新响应对象中存在的数组。
const getAPIresults = async () => {
await axios.get("https://newsapi.org/v2/top-headlines?country=us&apiKey=<mykeyhere>")
.then((response)=>{
console.log(response.articles);
setResults(response.articles);
})
.catch((error)=>{
console.log(error)
})
}但是它会抛出一个错误,说明结果是未定义的。甚至控制台现在也抛出未定义的。附错。有人能帮助解决这个问题吗?提前谢谢
发布于 2020-05-10 19:05:27
当axios接收到响应时,数据包含在响应的数据字段中,您应该将数据设置如下。
setResults(response.data.articles);https://stackoverflow.com/questions/61717150
复制相似问题