React报错Uncaught TypeError: recipes.map不是函数,求解决
问题描述
我是React.js新手,在RecipeList组件中渲染从接口获取的MongoDB食谱数据时,使用map方法遍历recipes状态出现Uncaught TypeError: recipes.map is not a function错误。以下是相关代码及报错信息:
RecipeList组件代码
import "./RecipeList.css"; import { Link, NavLink } from 'react-router-dom'; import React, { useEffect, useState } from 'react'; import RecipeModel from "../Recipe/RecipeModel/RecipeModel"; const RecipeList = () => { const [recipes,setRecipes] = useState([]); useEffect(() => { fetch('http://localhost:3005/api/recipes?page=1&limit=10') .then(res => res.json()) .then(result => { setRecipes(result) }); },[]); return ( <div> <section className="sec4"> <h1>Caponata pasta</h1> {recipes.map(x=> <RecipeModel key ={x._id} recipe={x}/>)} </section> <section className="sec5nav"> <ul> <li><Link smooth= "true" to="/"><i className="fas fa-solid fa-book-bookmark"></i></Link>Home</li> <li><Link smooth= "true" to="/recipes"><i className="fas fa-thin fa-bowl-rice"></i></Link>Recipes</li> <li><Link smooth= "true" to="/personal-list"><i className="fas fa-solid fa-list-ul"></i></Link>Your Recipes</li> <li><Link smooth= "true" to="/favourites"><i className="fa-solid fa-heart"></i></Link>Favourites</li> <li><Link smooth= "true" to="/create-recipe"><i className="fas fa-solid fa-plus"></i></Link>Add Recipe</li> <li><Link smooth= "true" to="/user-profile"><i className="fas fa-solid fa-user"></i></Link>Your Profile</li> </ul> <a href="#" className="to-top" id ="to-top"> <i className="fas fa-chevron-up"></i> </a> </section> </div> ); } export default RecipeList;
MongoDB Recipe Schema定义
const { Schema, model } = require('mongoose'); const recipeSchema = new Schema( { name: { type: String, required: true, minLength: [2, 'Name should be at least 5 characters long!'], }, time: { type: String, required: true, minLength: [2, 'Time should be in the format(10min)!'], }, imageUrl: { type: String, required: true, match: [/^https?:\/\/.+/, 'ImageUrl is not valid!'], }, ingredients: { type: String, required: true, minLength: [5, 'Ingredients should be at least 5 characters long!'], }, instructions: { type: String, required: true, minLength: [10, 'Instructions should be at least 10 characters long!'], }, isDeleted: { type: Boolean, default: false, }, }, { timestamps: true } ); const recipeModel = model('Recipe', recipeSchema); module.exports = { recipeModel, };
报错截图

问题排查与解决
这个错误的核心是**recipes状态被设置为非数组类型**,导致无法调用map方法,以下是具体排查和解决方式:
1. 检查接口返回数据结构
分页接口通常不会直接返回数组,而是返回包含数组的对象(比如带total、page等分页字段),例如:
{ "total": 20, "page": 1, "recipes": [/* 食谱数据数组 */] }
先打印接口返回结果确认结构,再提取正确的数组部分:
useEffect(() => { fetch('http://localhost:3005/api/recipes?page=1&limit=10') .then(res => res.json()) .then(result => { console.log('接口返回结果:', result); // 根据实际返回结构调整,比如取result.recipes setRecipes(result.recipes || []); }); },[]);
2. 处理接口请求错误
如果接口请求失败(后端报错),返回的可能是错误对象而非数组,需要添加错误处理:
useEffect(() => { fetch('http://localhost:3005/api/recipes?page=1&limit=10') .then(res => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .then(result => { setRecipes(result.recipes || []); }) .catch(err => { console.error('请求出错:', err); setRecipes([]); // 出错时保持状态为数组 }); },[]);
3. 渲染时兜底判断
在调用map前先确认recipes是数组,避免报错:
{Array.isArray(recipes) && recipes.map(x=> <RecipeModel key ={x._id} recipe={x}/>)}
内容的提问来源于stack exchange,提问作者DimitriTfb
相关产品推荐
相关产品推荐

