【发布时间】:2021-11-07 10:57:51
【问题描述】:
我有一个从 API 获取博客文章的应用程序。带有博客文章的 API 响应,我将这些博客文章发送到 GetBlogState 状态。当我使用 .map 遍历 GetBlogState 时,出现以下错误。
以下是我目前正在使用的代码。
import React, { useState, useEffect } from 'react';
import Head from 'next/head'
import axios from 'axios'
import HeaderComponent from '../components/HeaderComponent';
export default function Blog(){
const [GetBlogState, SetBlogState] = useState([]);
useEffect(() => {
axios.get('http://localhost:4000/blog').then(res => {
SetBlogState(res)
}).catch(errr => {
console.log(err)
})
}, []);
return (
<div className="MyApp">
{ GetBlogState.map(item => (
<div className="h-68">
<img className="w-full" alt="post" src='post.jpg' />
<div className="mt-3 mb-2 text-xs">May 10, 2018</div>
<h2 className="font-bold mb-5 text-xl"><a href="/" className="hover:underline">{ item.Title } </a></h2>
<p>{item.content}</p>
</div>
))}
</div>
)
}
【问题讨论】:
-
检查
res变量。它可以是一个对象、null、字符串……并且只有数组有map。