[英]Updating array inside array in React SetState?
One of the elements in state is happened to be nested array containing objects like below: state 中的元素之一恰好是包含如下对象的嵌套数组:
this.state = {
department: [
[
{
"name": {
"firstName": "John",
"lastName": "Joestar"
},
"age": 29
},
{
"name": {
"firstName": "George",
"lastName": "Thomas"
},
"age": 24
}
],
[
{
"name": {
"firstName": "Mary",
"lastName": "Jane"
},
"age": 40
}
]
]
}
Now suppose I need to update the firstName
at department[0][0].name.firstName
to Joseph.现在假设我需要将
department[0][0].name.firstName
的firstName
更新为 Joseph。 What is the correct way to update firstName
using setState
w/o compromising efficiency?在不影响效率的情况下使用
setState
更新firstName
的正确方法是什么?
You have to find the object, assign it to a variable, change it and set it again.您必须找到该对象,将其分配给一个变量,对其进行更改并重新设置。 Once you have a array of objects, and pick one of them if you change the object reference will be found.
一旦你拥有了一个对象数组,如果你改变对象引用就会找到其中的一个。
I'd somenthing like:我想要的是:
department: [
[
{
"name": {
"firstName": "John",
"lastName": "Joestar"
},
"age": 29
},
{
"name": {
"firstName": "George",
"lastName": "Thomas"
},
"age": 24
}
],
[
{
"name": {
"firstName": "Mary",
"lastName": "Jane"
},
"age": 40
}
]
]
....
const getDataToChange = this.state.department.find(dep => dep.name.firstName === "John");
getDataToChange.name.firstName = "Joseph"
this.setState(...this.state.department);
I think you can make a dummy or clone of your department array like this:我认为你可以像这样制作你的部门数组的虚拟或克隆:
var departmentClone = [...this.state.department]
And set like this:并设置如下:
departmentClone[0].name.firstName = 'Joseph'
this.setState({department: departmentClone})
Or more small code或者更小的代码
var department = [...this.state.department]
department[0].name.firstName = 'Joseph'
this.setState({department})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.