首页 > 解决方案 > 要存储在特定索引处的数组中的数据

问题描述

我有 8 个网格框,这 8 个框有 4 个属性

id, name, age, location

id 是可编辑的,而其他是带有 Textfield 的只读数据,因此我可以根据选择的 id 设置值。

现在onChange事件将传递两个参数(event,index)

例如 :

格子 1: event, "0" 格子 2: event, "1" 格子 3: event, "2" …………

所以,我正在索引进行硬编码,并且我有数组类型的状态变量

this.state={
 personData:[]
}

 handlePersonId = (event, index) =>{

      const { personData } = this.state;

      personData.push({id:'', name:'', age:'', location:''});
      personData[index].id=event.target.value;
      this.setState(this.state.personData);
    }  

如果我按顺序插入数据,它工作正常,但是当我输入网格框 2、3、4、...8 的 id 时,我会收到错误,因为我按顺序推送属性而不是索引而不是特定索引,因此我是变得未定义

预期输出:如果我在网格框 5 中输入,则传递索引4,事件目标值为23

[{},{},{},{},{id:'23', name:'Omkar', age:'22', location:'usa'}]

标签: javascriptreactjs

解决方案


如果我理解正确,您想要:

  • 根据对象中的数据更新数组id中现有的“人”项personDataevent
  • 如果不存在,则index在其中创建一个新的“人”personData
  • 确保一旦调用函数,personData数组中的项目(在 之前index)至少被初始化为空对象handlePersonId()

为此,您可以handlePersonId()按如下所示/记录的方式实现:

handlePersonId = (event, index) =>{

    this.setState(({ personData }) => {

        /* Extract id from event */
        const id = event.target.value;

        /* Clone person array */
        const cloneArray = [].concat(personData);

        /* Iterate index range from 0 to check for invalid person 
        entries and add an empty object if required */
        for(let i = 0; i < index; i++) {
            cloneArray[i] = cloneArray[i] || {};
        }

        if(cloneArray[index]) {
            /* Update id of person at index if person data already 
            exists */
            cloneArray[index].id = id;
        }
        else {
            /* Otherwise create a new person object at index */
            cloneArray[index] = {
                id, 
                name:'', 
                age:'', 
                location:''
            } 
        }

        /* Return new state */
        return { personData : cloneArray };    
    });
}

推荐阅读