javascript - 在页面上显示 api 数据时遇到问题?
问题描述
我正在制作一个项目,我从https://spoonacular.com获取食谱卡的图像,我希望它显示在我的 react.js 应用程序上。出于某种原因,当我运行它时,我无法在页面上显示 API 数据。请帮助我真的卡住了。我不断收到recipe.js 中recipeList 未定义的错误,但我认为它已定义?
这是我的 Home.js:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";
const URL = `https://api.spoonacular.com/recipes/716429/information?apiKey=${APIKey}&includeNutrition=false`;
function Home() {
const [food, setFood] = useState();
useEffect(() => {
if (food) {
axios
.get(URL)
.then(function (response) {
const recipeList = response.data;
setFood(recipeList);
})
.catch(function (error) {
console.warn(error);
});
}
}, [food]);
return (
<main>
<Recipe recipeList={food} />
</main>
);
}
export default Home;
这是我的 Recipe.js
import React from "react";
function Recipe({ recipeList }) {
return (
<div className="Recipe">
<div>{recipeList.title}</div>
<img src={recipeList.image} />
</div>
);
}
export default Recipe;
解决方案
你需要初始化为空
const [food, setFood] = useState({});
并在 useEffect 评估食物是否为空
useEffect(() => {
const getData=()=>{
axios
.get(URL)
.then(function (response) {
const {data} = response;
setFood(data);
})
.catch(function (error) {
console.warn(error);
});
}
if(!food){ // validate if food is empthy to get data (food)
getData()
}
}, []); // here is not necesary use food, because never happen anything with that variable
推荐阅读
- python - 在 matplotlib 中绘制图形时遇到问题
- python - 将两个字典键值与 pandas 数据框行匹配
- python - 使用 Python 选择特定的 Excel 输入并将它们保存到另一个 Excel 文件中?
- kotlin - 以“多态”方式处理对象列表的正确方法
- github - 注册;合并请求github时发现冲突
- laravel - Laravel 合集展示与短刊
- flutter - 还有其他方法可以显示 YouTube 网络视频吗?
- javascript - js 从样式代码元素中复制干净的代码
- docker - 如何在覆盖的 docker compose 文件中取消设置网络模式?
- qt - 如何确保 QWidget 在 QHBoxLayout 中水平居中?