Reactjs 反应组件嵌套对象数组
我是新手,在映射我的应用程序中的嵌套对象数组时遇到了一些问题,因为它是未定义的 这是我的api响应,它是一组配方Reactjs 反应组件嵌套对象数组,reactjs,react-component,Reactjs,React Component,我是新手,在映射我的应用程序中的嵌套对象数组时遇到了一些问题,因为它是未定义的 这是我的api响应,它是一组配方 const recipeMock = [ { "ingredientsInfo": [ { "ingredientId": { "_id": "609e1325f5bbf3301d24102c",
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,
})
作为回报,它会呈现一张卡片。但是,当映射Ingreditsinfo
如下时,麻烦就来了:
<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>
{Ingreditsinfo.map((成分,索引)=>(
-
{component.ingredientId.name}
{成分.gramsPerIngredient}克
))}
控制台告诉我“无法读取未定义的属性'map'。如果
Ingreditsinfo
或Ingreditsinfo
中没有数组,将遇到错误无法读取未定义的属性'map'
最好设置条件来检查数组的大小,如:
<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>
{ingredientsInfo&&ingredientsInfo.map((成分,索引)=>(
-
{component.ingredientId.name}
{成分.gramsPerIngredient}克
))}
根据错误和模拟,您使用了:
<RecipeCard {...recipeMock} />
而不是:
<RecipeCard {...recipeMock[0]} />
如果坚持不使用索引,请确保首先映射它,然后只映射它内部的InCreditsInfo
。首先,RecipeCard
函数不能接收recipeMock
对象作为其参数。在React中,功能参数用于从其他组件传递道具
其次,在访问ingredientsInfo
之前,必须映射到recipeMock
,因为两者都是数组。这意味着您必须嵌套两个映射函数,如下所示:
const recipeMock=[
{
ingredientsInfo:[
{
IngreditID:{
_id:“609e1325f5bbf3301d24102c”,
名称:“意大利面南瓜”
},
格拉姆斯佩里格朗特:301
},
{
IngreditID:{
_id:“609e1325f5bbf3301d24102b”,
名称:“意大利面南瓜”
},
格拉姆斯佩里格朗特:47
}
],
_id:“609e1326f5bbf3301d241242”,
}
];
const RecipeCard=()=>{
返回recipeMock.map({ingredientsInfo,_id})=>(
{Ingreditsinfo.map(
({gramsPerIngredient,ingredientId:{u id,name}})=>(
{gramsPerIngredient},{name}
)
)}
));
};
这里是中的一个工作演示。您能告诉我们从哪里获取数据以及如何存储数据吗?这可能是由于api调用不同步,可能有很多原因。。除非您展示一个更完整的代码示例,否则无法分辨。谢谢!是的,我映射了配方和成分,但只是InCreditSinfo返回了未定义的内容,所以我只是在问题中添加了这一部分,谢谢!我按照上面的答案解决了它。谢谢,它工作得很好,尽管ingredientsInfo总是会被填充,所以我不知道为什么它会变成未定义的,也许它会在初始化之前尝试映射它。无论如何,非常感谢,这正是正确的方法。