反应组件嵌套的对象数组

react component nested array of objects

我是 React 新手,我在映射我的应用程序中的嵌套对象数组时遇到了一些问题,因为它是未定义的。

这是我的 api 回复,它是一组食谱。

const recipeMock = [
{
    "ingredientsInfo": [
        {
            "ingredientId": {
                "_id": "609e1325f5bbf3301d24102c",
                "name": "spaghetti squash",
            },
            "gramsPerIngredient": 301
        },
        {
            "ingredientId": {
                "_id": "609e1325f5bbf3301d24102b",
                "name": "spaghetti squash",
            },
            "gramsPerIngredient": 47
        },
    ],
    "_id": "609e1326f5bbf3301d241242",
    "name": "pain de mie",
    "gramsPerRecipe": 223,
    "elabTime": 20,
    "carbs": 201,
    "proteins": 10,
    "calories": 605,
        "instructions": "hi",
        "picture": "https://unsplash.com/photos/ijlUGGnrZsI",
    },{...other recipes following same structure
}]

我创建了一个组件来绘制以下每个配方:

export default function RecipeCard({
  recipeId,
  recipeName,
  ingredientsInfo,
  elabTime,
  carbs,
  proteins,
  calories,
  instructions,
  picture,
  addRecipeToUser,
})

在 return 中呈现一张卡片。但是当映射 ingredientsInfo 如下时,麻烦就来了:

   <div className="recipeCard_ingredients">
    <ul className="recipeCard_ingredients_list">
      {ingredientsInfo.map((ingredient, index) => (
        <li key={index}>
          <Link to={`/ingredients/${ingredient.ingredientId.name}`}>
            {ingredient.ingredientId.name}
          </Link>
          <p>{ingredient.gramsPerIngredient} grams</p>
        </li>
      ))}
    </ul>
  </div>

控制台告诉我“无法读取未定义的 属性 'map'”。

如果ingredientsInfo出错或者ingredientsInfo没有数组就会遇到错误Cannot read property 'map' of undefined

最好设置条件来检查数组,例如:

<div className="recipeCard_ingredients">
<ul className="recipeCard_ingredients_list">
  {ingredientsInfo && ingredientsInfo.map((ingredient, index) => (
    <li key={index}>
      <Link to={`/ingredients/${ingredient.ingredientId.name}`}>
        {ingredient.ingredientId.name}
      </Link>
      <p>{ingredient.gramsPerIngredient} grams</p>
    </li>
  ))}
</ul>
</div>

根据错误和模拟,您使用了:

<RecipeCard {...recipeMock} />

而不是:

<RecipeCard {...recipeMock[0]} />

如果您坚持不使用索引,请确保先映射它,然后只映射 ingredientsInfo 内部。

首先,RecipeCard 函数不能接收 recipeMock 对象作为其参数。在 React 中,函数参数用于传递来自其他组件的 props。

其次,您必须先映射 recipeMock,然后才能访问 ingredientsInfo,因为两者都是数组。这意味着您必须像这样嵌套两个地图函数:

const recipeMock = [
  {
    ingredientsInfo: [
      {
        ingredientId: {
          _id: "609e1325f5bbf3301d24102c",
          name: "spaghetti squash"
        },
        gramsPerIngredient: 301
      },
      {
        ingredientId: {
          _id: "609e1325f5bbf3301d24102b",
          name: "spaghetti squash"
        },
        gramsPerIngredient: 47
      }
    ],
    _id: "609e1326f5bbf3301d241242",
  }
];
const RecipeCard = () => {
  return recipeMock.map(({ ingredientsInfo, _id }) => (
    <div key={_id}>
      {ingredientsInfo.map(
        ({ gramsPerIngredient, ingredientId: { _id, name } }) => (
          <p key={_id}>
            {gramsPerIngredient}, {name}
          </p>
        )
      )}
    </div>
  ));
};

这是 CodeSandbox 中的工作演示。