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,
})

其反过来呈现卡。但当映射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";。

如果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>

根据错误和mock,您使用了:

<RecipeCard {...recipeMock} />

代替:

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

如果你坚持在没有索引的情况下使用,那么一定要先映射它,然后只映射里面的ingredientsInfo

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

其次,在访问ingredientsInfo之前,必须在recipeMock上进行映射,因为两者都是数组。这意味着你必须嵌套两个类似的映射函数:

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

最新更新