[英]Why does data from my api only display once and when I refresh the page it gives an error
Im working on a project that displays a random food title and the image of that food.我正在研究一个显示随机食物标题和该食物图像的项目。 Im having trouble figuring out why the data displays on the page only once and once I refresh the page, it gives an error of "Uncaught TypeError: recipeList.recipes is undefined".我无法弄清楚为什么数据只在页面上显示一次,一旦我刷新页面,就会出现“未捕获的类型错误:recipeList.recipes 未定义”的错误。
This is my home.js这是我的 home.js
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({});
useEffect(() => {
axios
.get(URL)
.then(function (response) {
setFood(response.data);
})
.catch(function (error) {
console.warn(error);
});
}, []);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
and this is my Recipe.js component这是我的 Recipe.js 组件
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;
you should verify if you data food
is not empty or null, here an example:您应该验证您的数据food
是否不为空或为空,这里是一个示例:
<main>
{food &&
<Recipe recipeList={food} />}
</main>
first at all you need to load the datas in useeffect首先,您需要在 useEffect 中加载数据
useEffect(() => {
const loadData=()=>{
axios
.get(URL)
.then(function (response) {
setFood(response.data);
})
.catch(function (error) {
console.warn(error);
});
}
if(!food){ // just for dont load empty data -->setFood(response.data)
loadData()
}
}, []);
you are loading empty data when you reload the page重新加载页面时正在加载空数据
rn3w beat me to it. rn3w 打败了我。 The error message is indicating that recipeList.recipes
does not exist, which is correct because when the Recipe
component is initialized recipeList
( food
from the Home
component) is set to {}
.错误消息表明recipeList.recipes
不存在,这是正确的,因为在Recipe
组件初始化时recipeList
(来自Home
组件的food
)设置为{}
。
the data displays on the page only once and once I refresh the page, it gives an error...数据只在页面上显示一次,一旦我刷新页面,就会出现错误...
The mystery to me is why the data displays on the page the first time!对我来说神秘的是为什么数据第一次显示在页面上! Seems like it should start out with the error message.似乎它应该从错误消息开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.