[英]My Api data is not displaying on my react app
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
请帮助我真的卡住了
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/4632/card?apiKey=${APIKey}`;
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;
and this is my Recipe.js这是我的 Recipe.js
import React from "react";
function Recipe({ recipeList }) {
return (
<section className="RecipeCard">
<div
className="Recipe"
dangerouslySetInnerHTML={{ __html: recipeList }}
/>
</section>
);
}
export default Recipe;
You need to output the JSON as HTML for it to display.您需要将 JSON 输出为 HTML 才能显示。
For example, get a specific recipe : https://api.spoonacular.com/recipes/716429/information?includeNutrition=false例如,获取特定食谱: https : //api.spoonacular.com/recipes/716429/information?includeNutrition=false
and in the Recipe
Component div
并在
Recipe
组件div
<div className="Recipe">
<div>{recipeList.title}</div>
<img src={recipeList.image} />
</div>
<section className="RecipeCard">
{recipeList.map((recipe, index)=> (
<div key={index} className="Recipe">
<h2>{recipe.title}</h2>
</div>
))}
</section>
Also, for code readability try to use async-await syntax for API call.此外,为了代码可读性,尝试对 API 调用使用 async-await 语法。
useEffect(()=> {
const getRecipeList = async () => {
if(food){
try{
const { data } = await axios.get(URL);
setFood(data);
}catch(error){
console.log(error);
}
}
}
getRecipeList();
},[food]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.