繁体   English   中英

我的 Api 数据未显示在我的 React 应用程序上

[英]My Api data is not displaying on my react app

我正在制作一个项目,我从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;

您需要将 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>
 <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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM