javascript - 要存储在特定索引处的数组中的数据
问题描述
我有 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'}]
解决方案
如果我理解正确,您想要:
- 根据对象中的数据更新数组
id
中现有的“人”项personData
event
- 如果不存在,则
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 };
});
}
推荐阅读
- facebook - /act_{ad_account_ID}/users 请求时找不到有关响应错误的任何信息
- android - 如果应用程序在后台,Firebase 有时不会在一段时间后触发 onMessageReceived
- html - css 显示 flex 和换行
- c# - 基于datagrid c# wpf中的列从datagrid视图中禁用按钮
- html - 试图在引导程序 4 中居中弹性部分
- android - RecyclerView 会不定期更新
- angular - Angular 6显示应用程序引导的进度
- android - WINDOWS:不推荐使用“android”命令
- android-studio - 找不到项目所需的 com.project.expoview:26.0.0:Android Studio 中的应用程序?
- python - Pycharm:安装包后未解决的引用