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

React项目调用随机食谱API数据仅显示一次刷新报undefined错误如何解决

问题原因

报错本质是首屏渲染时异步接口还未返回数据导致的:

  • 你给food设置的初始值是空对象{},Home组件首次渲染时会直接把空对象传递给Recipe组件
  • 此时Recipe组件直接访问recipeList.recipes[0],空对象没有recipes属性,自然会抛出recipeList.recipes is undefined的错误
  • 首次加载正常是因为开发环境热更新会留存之前的状态,刷新页面后状态重置就会暴露问题
修复方案

你可以从以下几个常用方案中选适合的使用:

方案1:加可选链做安全取值(最简单,推荐)

直接修改Recipe组件的取值逻辑,用可选链做属性存在性校验,属性不存在时不会抛出错误,只会返回undefined:

import React from "react";

function Recipe({ recipeList }) {
  return (
    <div className="recipeCard">
      <h1>{recipeList.recipes?.[0]?.title}</h1>
      <img src={recipeList.recipes?.[0]?.image} alt="Food" />
    </div>
  );
}

export default Recipe;

方案2:新增loading状态判断

在Home组件中新增loading状态,接口未返回前展示加载提示,不渲染Recipe组件:

import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";

const URL = `https://api.spoonacular.com/recipes/random?apiKey=${APIKey}&number=1`;

console.log(URL);

function Home() {
  const [food, setFood] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios
      .get(URL)
      .then(function (response) {
        setFood(response.data);
      })
      .catch(function (error) {
        console.warn(error);
      })
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div>加载中...</div>

  return (
    <main>
      <Recipe recipeList={food} />
    </main>
  );
}

export default Home;

方案3:给状态设置默认结构

给food的初始值设置默认的recipes数组,避免初始访问时报错:

// 修改home.js中的useState初始值即可
const [food, setFood] = useState({
  recipes: []
});

内容的提问来源于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 12:06:05