【问题标题】:How to map an array with custom index in React JS如何在 React JS 中使用自定义索引映射数组
【发布时间】:2018-11-13 10:08:30
【问题描述】:

我有一个状态为的值数组

constructor {
    super(props);
    this.state = {
        staff: {
                pos1: { name:'Ajith'}
                pos2: { name:'Ben'}
              }
    }
}
componentDidMount() {
    this.state.staff.map((item,index) => {
        console.log(item+" * "+index)
    }
}

我收到错误 this.state.staff.map is not a function,因为索引与 0, 1 etc 不同。我该如何解决这个问题?

【问题讨论】:

  • 因为 this.state.staff 不是数组!!。这是一个对象
  • loop on object的可能重复

标签: reactjs


【解决方案1】:

根据您的问题,这里有几点需要注意,

Staff 不是数组,所以你不能使用 map,为了使用 map,你需要 object.keys。

此外,您在人员值部分中缺少逗号。

       staff:  {
            pos1: { name:'Ajith'},
            pos2: { name:'Ben'}
          }

使用地图:

  Object.keys(staff).map((data) => staff[data].name )

It will return the output as:

["Ajith", "Ben"]

【讨论】:

    【解决方案2】:

    因为staffObject 而不是Array,所以你不能映射staff。不过你可以试试这个

    Object.key(this.state.staff).map((key, index) => { const item = this.state.staff[key] console.log(item+" * "+index) })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 2020-03-14
      • 2022-08-04
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多