React调用Spoonacular API渲染数据时recipeList未定义报错如何解决
问题修复方案
核心问题说明
- 状态初始值为空:
food状态没有设置初始值,首次渲染时传入Recipe组件的recipeList为undefined,直接访问其属性会触发报错 - 请求触发逻辑错误:useEffect中设置了
if (food)才发送接口请求,但初始状态下food是空值,接口永远不会调用,food永远不会被赋值 - 缺少空值兼容:没有做加载状态判断,接口请求完成前直接渲染子组件会触发空值访问错误
- 额外注意:代码中URL拼接的
APIKey变量需要确保你已经提前正确定义,否则接口会返回鉴权失败错误
修复后代码
Home.js
import React, { useEffect, useState } from "react"; import axios from "axios"; import Recipe from "../components/Recipes"; // 注意此处需要替换为你自己的实际APIKey const APIKey = "你的spoonacular平台API密钥"; const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`; function Home() { // 初始值设为null,方便判断加载状态 const [food, setFood] = useState(null); // 依赖项改为空数组,组件挂载时仅触发一次请求 useEffect(() => { axios .get(URL) .then(function (response) { setFood(response.data); }) .catch(function (error) { console.warn(error); }); }, []); return ( <main> {/* 加载状态判断,数据返回后再渲染Recipe组件 */} {food ? <Recipe recipeList={food} /> : <div>加载中...</div>} </main> ); } export default Home;
Recipe.js
import React from "react"; function Recipe({ recipeList }) { return ( <div className="Recipe"> {/* 可选链兼容空值,同时img标签补充alt属性避免React警告 */} <div>{recipeList?.title}</div> <img src={recipeList?.image} alt={recipeList?.title || "食谱图片"} /> </div> ); } export default Recipe;
内容的提问来源于stack exchange,提问作者mw3981
相关产品推荐
相关产品推荐

