下面是获取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获取加载文本显示在主页上,但一旦获取,Map上就看不到任何数据,尽管获取的数据在控制台上清晰可见
很抱歉几乎贴出了整个代码。
1条答案
按热度按时间omhiaaxx1#
根据您的代码,我可以看到您正在解构结果,但没有在setrecipes中正确设置,您必须在setloadingstate(false)之后像这样设置setrecipes(results);在if条件内。