gpt4 book ai didi

javascript - 如何更新React Native中的数组?

转载 作者:行者123 更新时间:2023-12-01 01:01:37 25 4
gpt4 key购买 nike

如何通过更改其中一个对象来更新数组?

这将是我的数组代码

this.datas = [
{
index: 1,
name: 'Tony',
status: 'Absent',
reason: null
},
{
index: 2,
name: 'Chris',
status: 'Present',
reason: null
},
];

所以现在我想编写一个函数来更新原因,例如 {reason: any Reason},索引 1、索引 2 保持不变。

到目前为止我已经尝试过这些

setReason = reason => {

let data = [...this.state.nameList];
let ind = data.findIndex(el => el.index === 'number');
data[ind] = { ...data[ind], reason: reason };
this.setState({
nameList: data
});
};

最佳答案

更新数组的单个对象数据您首先需要知道要更新的对象在数组中的索引例如想要更新数组的第一个对象

this.datas[0].reason = 'My custom reason';

现在你想通过查找数组中的对象来更新数组的对象,你必须在其中添加一个循环例如:更新原因,其中 name = Chris

for(i=0; i<this.datas.length; i++){
if(this.datas[i].name=='Chris'){
this.datas[i].reason = 'My custom reason';
break;
}
}

关于javascript - 如何更新React Native中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56017034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com