简体   繁体   English

仅当有数组时,我如何使用.map()?

[英]How can i use .map() only when there is an array?

I am new to react and I am passing an item prop.我是新手,我正在传递一个物品道具。 Some of the items has an empty array in items.modifiers.一些项目在 items.modifiers 中有一个空数组。 When I use an if an if condition i still get an error that "Cannot read property 'map' of undefined " Below is my code.当我使用 if 条件时,我仍然收到“无法读取未定义的属性‘映射’”的错误,下面是我的代码。 Any help would be really appreciated.任何帮助将非常感激。

const NewModal = ({ item }) => {
  if (item.modifiers !== "") {
    item.modifiers.map((modifier) => console.log(modifier.cat_name));
  }
};

return [
  {
    items: [
      {
        item_id: 1,
        item_name: "Philadelphia Steak Sandwich",

        modifiers: {
          cat_name: " Choose a side",
          mod_items: [
            { mod_item_name: "French Fries", price: 1 },
            { mod_item_name: "Cole Slaw", price: 2 },
          ],
        },
      },
      {
        item_id: 2,
        item_name: "Philadelphia Steak Sandwich Deluxe",

        modifiers: "",
      },
    ],
  },
];

Use Array.isArray() first to check whether the item you're trying to map is of type Array.首先使用Array.isArray()检查您尝试 map 的项目是否属于 Array 类型。

 const NewModal = ({item}) => { if(Array.isArray(item.modifiers) { item.modifiers.map((modifier)=> console.log(modifier.cat_name)); } }

You need to ensure your data is an array in the first place.您首先需要确保您的数据是一个数组。 Then you can check whether the array is ready or not.然后您可以检查阵列是否准备就绪。

You should ensure data type is consistent, this is a given.您应该确保数据类型一致,这是给定的。

While waiting for the data to populate (probably from an API call), instead of if-else you can use null propagation operators / optional chaining在等待数据填充时(可能来自 API 调用),而不是 if-else 您可以使用null 传播运算符/可选链接

Then you can call something like this with a single question mark before the dot.然后你可以在点之前用一个问号来调用这样的东西。

const newArray = item?.modifier?.map(item => do something)

This way it will suppress the undefined error.这样它将抑制未定义的错误。

Another step you need to take is conditional rendering.您需要采取的另一个步骤是条件渲染。

For example例如

if (!data?.length) return null

//OR

if (!data?.length) return <div>data is loading</div>

You can simply do that by checking if every required condition is met and then by looping the modifiers array,您可以通过检查是否满足每个必需的条件然后循环修饰符数组来简单地做到这一点,

item && item.modifiers && item.modifiers.length && item.modifiers.map((modifier)=> console.log(modifier.cat_name))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM