【问题标题】:react component nested array of objects反应组件嵌套的对象数组
【发布时间】:2021-05-15 20:30:02
【问题描述】:

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

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

作为回报,它会呈现一张卡片。但是映射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'”。

【问题讨论】:

  • 你能说明你在哪里获取数据以及如何存储它吗?这可能是由于异步 api 调用
  • 可能有很多原因。除非您显示更完整的代码示例,否则无法判断。

标签: reactjs react-component


【解决方案1】:

如果ingredientsInfoingredientsInfo没有数组有错误会遇到错误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>

【讨论】:

  • 谢谢,它工作得很好,虽然成分信息总是会被填充,所以我真的不知道为什么它变成未定义,也许它会在初始化之前尝试映射它。无论如何,非常感谢,这是正确的方法。
【解决方案2】:

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

<RecipeCard {...recipeMock} />

代替:

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

如果你坚持不使用索引,那么请确保先映射它,然后只在其中映射ingredientsInfo

【讨论】:

    【解决方案3】:

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

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

    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 中的工作演示。

    【讨论】:

    • 谢谢!是的,我映射了 recipesMock 和成分,但只是成分信息返回未定义,所以我只是将这部分添加到问题中,谢谢!我按照上面的答案解决了。
    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多