Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用axios的API请求的结果在我的React本机代码中返回未定义的结果,但在控制台中正确记录_Reactjs_React Native_Axios_Restapi - Fatal编程技术网

Reactjs 使用axios的API请求的结果在我的React本机代码中返回未定义的结果,但在控制台中正确记录

Reactjs 使用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

下面的代码在控制台中打印响应,但当使用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 [ 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);