首页 > 解决方案 > 使用 axios 的 API 请求结果在我的 React Native 代码中返回 undefined 但在控制台中正确记录

问题描述

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

我将一个空数组初始化为结果,但响应将是一个对象。所以,我试图分配一个数组而不是一个对象。在 React 中没关系,但我尝试更新响应对象中存在的数组。

响应 json 对象有文章数组

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)
          })    
}

但它会抛出一个错误,说结果未定义。甚至控制台现在也抛出未定义附加错误。任何人都可以帮助解决这个问题吗?提前致谢

标签: reactjsreact-nativeaxiosrest

解决方案


当 axios 收到响应时,数据包含在响应的数据字段中,您应该将数据设置如下。

 setResults(response.data.articles);

推荐阅读