Reactjs 如何在React JS中映射具有自定义索引的数组

Reactjs 如何在React JS中映射具有自定义索引的数组,reactjs,Reactjs,我有一个状态为的值数组 constructor { super(props); this.state = { staff: { pos1: { name:'Ajith'} pos2: { name:'Ben'} } } } componentDidMount() { this.state.staff.map((item,index) => {

我有一个状态为的值数组

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不是一个函数
,因为索引不是
0,1等
。如何修复此问题?

因为
员工
对象
而不是
数组
,因此无法映射
员工
。但是你可以试试这个

Object.key(this.state.staff).map((key,index)=>{
const item=此.state.staff[键]
console.log(项+“*”+索引)

})

根据您的问题,这里需要注意的几件事

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"]

因为this.state.staff不是数组!!。这是一个可能的复制品