Javascript 从API访问数组中的单个元素(react)
我是一个初学者,我正在尝试创建一个食谱应用程序。我设法建立了一个API,每次我搜索一顿这样的饭时,它都会给出一个包含10个对象的数组 我使用地图访问每个配方的元素Javascript 从API访问数组中的单个元素(react),javascript,html,reactjs,api,Javascript,Html,Reactjs,Api,我是一个初学者,我正在尝试创建一个食谱应用程序。我设法建立了一个API,每次我搜索一顿这样的饭时,它都会给出一个包含10个对象的数组 我使用地图访问每个配方的元素 {recipes.map(recipe =>( <RecipeCard key={recipe.recipe.label} title ={recipe.recipe.label} calories={recipe.recipe.calories} image={recipe.recip
{recipes.map(recipe =>(
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
))}
{recipes.map(recipe=>(
))}
这也是我的Const配方卡,只是为了了解更多的上下文。它的功能很好
const RecipeCard = ({title, calories, image, ingredients}) => {
const round = Math.round(calories);
return(
<div className = {style.recipe}>
<h1 >{title}</h1>
<ol className = {style.list}>
{ingredients.map(ingredient => (
<li>{ingredient.text}</li>
))}
</ol>
<p>calories: {round} </p>
<img className = {style.image} src={image} alt=""/>
<button>Add to Favorites</button>
</div>
)
}
const RecipeCard=({标题、卡路里、图像、配料})=>{
常量回合=数学回合(卡路里);
返回(
{title}
{配料.map(配料=>(
{component.text}
))}
卡路里:{round}
添加到收藏夹
)
}
我目前只想访问第一个数组中的信息,但每当我将recipes.map更改为recipes[0]时,它都会说该函数不存在。我应该如何从API提供的数组中访问单个元素?您可以使用创建浅拷贝(仅包含第一个元素的新数组):
调用
?。
时,您可以使用它来避免诸如无法读取未定义的属性之类的错误,即当第一个元素是未定义的
并且您尝试读取其属性时。您所说的“第一个数组”是什么意思?您的示例中只有一个数组…非常感谢!我一直在谷歌和youtube上搜索,但找不到答案。我非常感激。
{recipes.slice(0, 1).map(recipe =>(
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
))}
const [recipe] = recipes // before "return"
// ....
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
<RecipeCard
key={recipes[0]?.recipe.label}
title ={recipes[0]?.recipe.label}
calories={recipes[0]?.recipe.calories}
image={recipes[0]?.recipe.image}
ingredients={recipes[0]?.recipe.ingredients}
/>