【问题标题】:Access Individual Elements in an Array from an API (react)从 API 访问数组中的单个元素(反应)
【发布时间】:2021-07-10 22:38:27
【问题描述】:

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

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

{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] 时,它都会说该函数不存在。我应该如何从 API 提供的数组中访问单个元素?

【问题讨论】:

  • 第一个数组是什么意思?您的示例中只有一个数组...

标签: javascript html reactjs api


【解决方案1】:

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

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

或者使用destructuring:

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

?.被称为optional chaining,你可以用它来避免像Can't Read property of undefined这样的错误,即当第一个元素是undefined并且你尝试读取时它的属性。

【讨论】:

  • 非常感谢!我一直在寻找谷歌和youtube,但找不到答案。非常感谢。
猜你喜欢
  • 2022-01-15
  • 2016-08-13
  • 1970-01-01
  • 2019-01-17
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多