[英]How to map through and store an API response as an array of objects in state React JS
I am trying to map through a server side API response to store first three items in state as an array of objects with title and url key/value pairs. 运行此代码时,我收到“对象作为 React 子项无效”错误。 如何正确地将对象推送到我的文章 useState 数组,以便我可以在数组上 map 以将它们呈现为我页面上的链接? 谢谢...
const CodeNews = () => {
const [articles, setArticles] = useState([])
useEffect(() => {
axios.get('http://localhost:8000/apiKey')
.then((res)=>{
console.log(res)
let tempArr = [];
for(let i=0;i < 3; i++){
tempArr.push({
title: res.data.articles[i].title,
url: res.data.articles[i].url
})
}
setArticles(tempArr);
})
.catch((err)=>console.log(err))
},[])
可能解决方案是将渲染方法更改为如下所示:
articles.map((el) => (
<a href={el.url}>{el.title}</a>
))
这是因为你不能在 JSX 中渲染整个 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.