【问题标题】:map an array with index keys to return a list of items react JS使用索引键映射数组以返回项目列表 react JS
【发布时间】:2020-01-29 14:57:10
【问题描述】:

我在这里有一个数组,我想将它映射出来并在单选复选框中列出。

我目前只能通过输入例如:<IonLabel>{item[1]}</IonLabel> 来返回数组中的一项

我怎样才能让他们都列出来?

'设备'数组

{0: "Camera", 1: "Wide Angle Lens (16mm equivalent)", 2: "Tripod", 3: "Drone"}

0: "Camera"
1: "Wide Angle Lens (16mm equivalent)"
2: "Tripod"
3: "Drone"

当前代码

{equipment.map((item, i) => {
          return (
        <IonItem key={i}>
         <IonLabel>{item}</IonLabel>
         <IonRadio slot="start" value="biff"/>
        </IonItem>

          );
        })}

【问题讨论】:

    标签: arrays reactjs list arraylist


    【解决方案1】:

    看起来您使用的不是数组,而是一个以数字为键的对象。

    试试这个:

    {
      Object.values(equipment).map((item, i) => (
         <IonItem key={i}>
           <IonLabel>{item}</IonLabel>
           <IonRadio slot="start" value="biff"/>
         </IonItem>
       )
      );
    }
    
    

    另一种解决方案可能是将您的 equipment 重写为:

    const equipment = ["Camera", "Wide Angle Lens (16mm equivalent)", "Tripod", "Drone"] 在这种情况下,您可以使用之前的实现。

    【讨论】:

      【解决方案2】:

      你在这里拥有的不是一个数组,而是一个对象。

      您可以将数据存储在这样的数组中:

      ['Camera', 'Wide Angle Lens (16mm equivalent)', 'Tripod', 'Drone']
      

      现在您可以使用 map 对其进行迭代,就像您在示例中所做的那样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-13
        • 2020-04-18
        • 2018-08-22
        • 2021-02-09
        • 2015-05-15
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多