繁体   English   中英

从 API 访问数组中的单个元素(反应)

[英]Access Individual Elements in an Array from an API (react)

我是一个初学者,我正在尝试创建一个食谱应用程序。 我设法设置了一个 API,每次我像这样搜索一顿饭时,它都会给出一个包含 10 个对象的数组。

文本

我使用 map 访问每个配方的元素

{recipes.map(recipe =>(
   <RecipeCard 
   key={recipe.recipe.label}
   title ={recipe.recipe.label} 
   calories={recipe.recipe.calories}
   image={recipe.recipe.image}
   ingredients={recipe.recipe.ingredients}
    />
   ))}

这也是我的 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>
        )
    }

我目前只想访问第一个数组中的信息,但是每当我将 recipes.map 更改为 recipes[0] 时,它都会说 function 不存在。 我应该如何 go 关于从 API 提供的 arrays 访问各个元素?

您可以使用.slice(0, 1)创建一个浅拷贝(一个只有第一个元素的新数组):

{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}
/>

或使用index

<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}
/>

?. 被称为可选链接,您可以使用它来避免像Can't Read property of undefined 之类的错误,即当第一个元素undefined并且您尝试读取其属性时。

暂无
暂无

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

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