我正在制作一個專案,我從https://spoonacular.com獲取食譜卡的影像,我希望它顯示在我的 react.js 應用程式上。出于某種原因,當我運行它時,我無法在頁面上顯示 API 資料。請幫助我真的卡住了
這是我的 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;
這是我的 Recipe.js
import React from "react";
function Recipe({ recipeList }) {
return (
<section className="RecipeCard">
<div
className="Recipe"
dangerouslySetInnerHTML={{ __html: recipeList }}
/>
</section>
);
}
export default Recipe;
uj5u.com熱心網友回復:
您需要將 JSON 輸出為 HTML 才能顯示。
例如,獲取特定食譜:https : //api.spoonacular.com/recipes/716429/information?includeNutrition=false
并在Recipe組件中div
<div className="Recipe">
<div>{recipeList.title}</div>
<img src={recipeList.image} />
</div>
uj5u.com熱心網友回復:
<section className="RecipeCard">
{recipeList.map((recipe, index)=> (
<div key={index} className="Recipe">
<h2>{recipe.title}</h2>
</div>
))}
</section>
此外,為了代碼可讀性,嘗試對 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]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329675.html
標籤:javascript 反应
上一篇:從函式打字稿回傳字串
