Reactjs 使用axios的API请求的结果在我的React本机代码中返回未定义的结果,但在控制台中正确记录
下面的代码在控制台中打印响应,但当使用useState的setResults方法将其更新为结果时,它不起作用。它在JSX代码中不打印任何内容来代替result.lengthReactjs 使用axios的API请求的结果在我的React本机代码中返回未定义的结果,但在控制台中正确记录,reactjs,react-native,axios,restapi,Reactjs,React Native,Axios,Restapi,下面的代码在控制台中打印响应,但当使用useState的setResults方法将其更新为结果时,它不起作用。它在JSX代码中不打印任何内容来代替result.length import React, { useState } from 'react'; import {Text, View, StyleSheet,Button } from 'react-native' import axios from 'axios' const WeatherAPI = () => { const
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>
)
}
import React,{useState}来自“React”;
从“react native”导入{文本、视图、样式表、按钮}
从“axios”导入axios
常数WeatherAPI=()=>{
const[results,setResults]=useState([]);
const getAPIresults=async()=>{
等待axios。获取(“https://newsapi.org/v2/top-headlines?country=us&apiKey=")
。然后((响应)=>{
控制台日志(响应);
结果(应答);
})
.catch((错误)=>{
console.log(错误)
})
}
返回(
我们得到了{results.length}项
{getAPIresults()}}/>
)
}
我将空数组初始化为results,但响应将是一个对象。因此,我尝试分配一个数组而不是一个对象。这在React中并不重要,但我尝试更新响应对象中存在的数组
const getAPIresults=async()=>{
等待axios。获取(“https://newsapi.org/v2/top-headlines?country=us&apiKey=")
。然后((响应)=>{
console.log(response.articles);
setResults(response.articles);
})
.catch((错误)=>{
console.log(错误)
})
}
但它会抛出一个错误,称结果未定义。甚至控制台现在也会抛出未定义的。
. 有人能帮助解决这个问题吗?提前感谢当axios收到响应时,数据包含在响应的数据字段中,您应按以下方式设置数据
setResults(response.data.articles);
setResults(response.data.articles);