【发布时间】: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 调用
-
可能有很多原因。除非您显示更完整的代码示例,否则无法判断。