You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:36:01