繁体   English   中英

我无法使用 map api 数据数组 我在过去两天尝试了几种方法

[英]i am not able to map the api data array i have tried several methods from last two days

这是获取 api 食谱并将它们打印为卡片的简单代码:

import { useState } from "react";
import RecipeItem from "../../components/recipe-item";
import Search from "../../components/search";

const Homepage = () => {
  const [loadingstate, setloadingstate] = useState(false);

  const [recipes, setrecipes] = useState([]);

  const getdatafromsearchcomponent = (searchdata) => {
    setloadingstate(true);

    async function getrecipes() {
      const apiresponse = await fetch(
        `https://api.spoonacular.com/recipes/complexSearch?apiKey=2aa0ee8853c34e1f9783e0f882c40f38&query=${searchdata}`
      );
      const result = await apiresponse.json();
      const { results } = result;

      if (results && results.length > 0) {
        setloadingstate(false);
        setrecipes();
      }
      console.log(result);
    }
    getrecipes();
  };

  console.log(loadingstate, recipes, "loadingstate recipes");


  return (
    <div className="homepage">
      <Search getdatafromsearchcomponent={getdatafromsearchcomponent} />

      {loadingstate && (
        <div className="loadingmsg">loading.... please wait</div>
      )}
      {
       recipes && recipes.length>0?
       recipes.map((item)=>           /*THIS PART IS NOT WORKING*/
       <RecipeItem  item={item} />)
       :null
       }
    </div>
  );
};
export default Homepage;

下面的配方项目组件:

const RecipeItem=(props)=>{
    console.log(props,'recipe-item-props');
    return(
        <div>
            search result
        </div>
    )
}
export default RecipeItem;

我正在尝试 map 我从 spoonacular api 获取的食谱它的 fetchinf 很好并在控制台中显示数据但是当我尝试 map 它在主页上时不起作用

我试图将搜索组件合并到主页,但这也没有用。

即使加载部分工作正常 api 获取加载文本显示在主页上,但是一旦获取结束,映射上就看不到任何数据,尽管获取的数据在控制台上清晰可见

很抱歉几乎发布了整个代码。

根据你的代码,我可以看到你正在解构结果但没有在 setrecipes 中正确设置,你必须在 setloadingstate(false) 之后像这样设置它 setrecipes(results); 在 if 条件内。

暂无
暂无

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

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