reactjs 如何使用React在数组对象中渲染数组?

fjaof16o  于 2023-03-12  发布在  React
关注(0)|答案(2)|浏览(163)

如何在React中使用.map()获取recipeName?
下面是我的虚拟数据的食谱。

const recipe = [
  {
    category: 'Keto',
    name: 'Chicken Bistek',
    calories: '500',
    description: '',
    recipes: [
      {
        recipeName: 'Chicken',
        recipeSize: '3 lbs',
      },
      {
        recipeName: 'Garlic',
        recipeSize: '4 cloves',
      },
      {
        recipeName: 'Onion',
        recipeSize: '1 whole',
      },
      {
        recipeName: 'Soy Sauce',
        recipeSize: '1/4 cup',
      },
      {
        recipeName: 'Coconut Oil',
        recipeSize: '1 tbsp',
      },
      {
        recipeName: 'Water',
        recipeSize: '1 cup',
      },
    ],
  },
];

我试过下面的代码,但是它不能显示菜谱数组。它显示名称,类别。但是recipe.recipeName和recipe.recipeSize不能在标签中显示。

const DietList = (props) => {
  return (
    <>
      {props.diets.map((diet) => (
        <div key={diet.name}>
          <a>{diet.name}</a>
          <a>{diet.category}</a>
          {diet.recipes.map((recipe) => (
            <a key={recipe.recipeName}>{recipe.recipeSize}</a>
          ))}
        </div>
      ))}
    </>
  );
};
aelbi1ox

aelbi1ox1#

您的代码没有问题,只是没有显示recipeName

<>
   {props.diets.map((diet) => (
          <div key={diet.name}>
            <a>{diet.name}</a>
            <a>{diet.category}</a>
            <span>
              {diet.recipes.map((recipe) => (
// i added span so that we can add multiple tags
                <span key={recipe.recipeName}> 

                  <a>{recipe.recipeSize}</a>
                  <a>{recipe.recipeName}</a> 
                </span>
              ))}
            </span>
          </div>
        ))}
      </>
ufj5ltwl

ufj5ltwl2#

在这里,我利用你的虚拟数据:

{
       recipe.map((item, index) => {
         return (
           <div key={index}>
               <span>{item.category}</span>
               <br />
               <span>{item.name}</span>
               <div>
                {
                  item.recipes.map((r, index) => {
                    return (
                      <>
                        <span key={index} >{r.recipeName}: {r.recipeSize}</span><br />
                      </>
                    )
                  })
                }
               </div>
           </div>
         )
       })
     }

我不知道你为什么要用a标签,除非你要用href标签链接它。
但是我已经在Map中使用了return,它工作的很好。希望,它也能为你工作。

相关问题