[英]Having trouble displaying api data on the page?
Im making a project where I fetch an image of a recipe card from https://spoonacular.com and I want it displayed on my react.js app.我正在制作一个项目,我从https://spoonacular.com获取食谱卡的图像,我希望它显示在我的 react.js 应用程序上。 For some reason I can't get the API data from displaying on the page when I run it.
出于某种原因,当我运行它时,我无法在页面上显示 API 数据。 Please help Im really stuck.
请帮助我真的卡住了。 I keep getting the error that recipeList is undefined in Recipe.js but I thought it was defined?
我不断收到 Recipe.js 中未定义 recipeList 的错误,但我认为它已定义?
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/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;
this is my Recipe.js这是我的 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;
you need initializing empty你需要初始化为空
const [food, setFood] = useState({});
and in useEffect evaluate if food is empty并在 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
The response example can be seen here .可以在此处查看响应示例。
To call that using axios:使用 axios 调用它:
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(() => {
// You can add any if-else statement here
// but you can also do the fetch without it
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 based on the response, your Recipe.js
should working properly.根据响应,您的
Recipe.js
应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.