如何在状态 React JS 中映射 API 响应并将其存储为 objects 的数组

How to map through and store an API response as an array of objects in state React JS

我正在尝试通过服务器端 API 响应进行映射,以将状态中的前三项存储为具有标题和 url key/value 对的 objects 数组.当我 运行 这段代码时,我收到一个“objects 作为 React children 无效”的错误。我如何正确地将 objects 推送到我的文章 useState 数组,以便我可以映射数组以将它们呈现为我页面上的链接?谢谢...

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 中呈现整个对象。