React中useState存储的接口返回博客数据调用.map方法渲染报错如何解决?
错误原因
- 你直接将axios返回的完整响应对象赋值给了状态
GetBlogState,axios返回的响应对象里,接口返回的实际数据存放在res.data字段中,你当前赋值给状态的不是预期的博客数组,因此不存在map方法触发报错。 - 代码中存在拼写错误:catch回调的参数写为
errr,但打印时写的是err,变量名不一致会导致请求报错时无法正常打印错误信息,增加排查难度。
修正方案
- 将
SetBlogState(res)改为SetBlogState(res.data),确保状态存储的是接口返回的博客数组。 - 修正catch里的变量名错误。
- 渲染时添加可选链
?.调用map方法,避免极端情况下状态不是数组导致页面崩溃。 - map遍历渲染列表元素时,需要给每个子元素加唯一的key属性,避免React抛出性能警告。
修正后代码
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 => { // 取res.data里的实际数据赋值 SetBlogState(res.data) }).catch(err => { // 修正变量名拼写错误 console.log(err) }) }, []); return ( <div className="MyApp"> {/* 添加可选链避免报错,添加key属性 */} { GetBlogState?.map(item => ( <div className="h-68" key={item.id}> <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> ) }
内容的提问来源于stack exchange,提问作者Red Virus
相关产品推荐
相关产品推荐

