【问题标题】:Results of API request using axios returns undefined in my React Native code but logs correctly in Console使用 axios 的 API 请求结果在我的 React Native 代码中返回 undefined 但在控制台中正确记录
【发布时间】:2020-05-10 18:50:51
【问题描述】:

我下面的代码在控制台中打印响应,但是当使用 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 中没关系,但我尝试更新响应对象中存在的数组。

response json object has articles array

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

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

【问题讨论】:

    标签: reactjs react-native axios rest


    【解决方案1】:

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

     setResults(response.data.articles);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2022-12-03
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      相关资源
      最近更新 更多