【发布时间】: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)
})
}
但它会抛出一个错误,说结果未定义。甚至控制台现在也会抛出 undefined 。 Error Attached。任何人都可以帮助解决这个问题吗?提前致谢
【问题讨论】:
标签: reactjs react-native axios rest