React应用无法显示Spoonacular API返回的食谱卡片数据求助
问题排查与修复方案
核心问题汇总
- useEffect 触发逻辑错误:你当前的useEffect依赖设置为
food,且加了if (food)的判断才发起请求,而food的初始值为undefined,逻辑上就变成只有food有值时才会发请求拿数据,初始状态下请求永远不会触发,自然拿不到数据。 - 未处理空值渲染异常:初始
food为undefined,直接传给Recipe组件后调用dangerouslySetInnerHTML会直接抛出渲染错误。 - APIKey 变量缺失:URL模板中使用的
${APIKey}需要提前定义为你在spoonacular平台申请的有效密钥,否则会返回401权限错误导致请求失败。
修正后的代码
Home.js
import React, { useEffect, useState } from "react"; import axios from "axios"; import Recipe from "../components/Recipes"; // 替换为你自己的spoonacular平台有效API密钥 const APIKey = "你的实际API密钥"; const URL = `https://api.spoonacular.com/recipes/4632/card?apiKey=${APIKey}`; function Home() { const [food, setFood] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { axios .get(URL) .then(function (response) { setFood(response.data); }) .catch(function (error) { console.warn(error); setError("接口请求失败,请检查API密钥或网络配置"); }) .finally(() => { setLoading(false); }); // 依赖数组留空,保证组件挂载时仅发起一次请求 }, []); if (loading) return <div>加载中...</div>; if (error) return <div>{error}</div>; return ( <> <main> <Recipe recipeList={food} /> </main> </> ); } export default Home;
Recipe.js
import React from "react"; function Recipe({ recipeList }) { if (!recipeList) return null; return ( <section className="RecipeCard"> <div className="Recipe" dangerouslySetInnerHTML={{ __html: recipeList }} /> </section> ); } export default Recipe;
内容的提问来源于stack exchange,提问作者mw3981
相关产品推荐
相关产品推荐

