reactjs - 使用 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 中没关系,但我尝试更新响应对象中存在的数组。
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)
})
}
但它会抛出一个错误,说结果未定义。甚至控制台现在也抛出未定义。 附加错误。任何人都可以帮助解决这个问题吗?提前致谢
解决方案
当 axios 收到响应时,数据包含在响应的数据字段中,您应该将数据设置如下。
setResults(response.data.articles);
推荐阅读
- php - 使用 laravel 模型获取数据时没有从表中获取结果
- git - 将一些 SVN 项目迁移到现有的 Git 存储库中
- matlab - 如何生成具有给定密度的稀疏复值酉矩阵?
- javascript - 退出页面的消息仅适用于 Edge 而不是 Chrome 和 Firefox
- ios - 发布的视图模型成员值更改时视图上的 SwiftUI 运行方法
- java - 你如何计算你自己的位置和标记之间的距离,并让它只有在足够近的时候才能点击?
- php - 在笔记本电脑上下载图像,但不能在智能手机上下载
- ios - 如何在使用 webview 播放视频时检测我何时处于全屏状态
- python - 为什么不使用 Scipy 的 FFT 代码中的结果与 Scipy FFT 不相似?
- reactjs - React useEffect 缺少依赖错误,但它在那里