Suppose I have an array of people:
this.state = {
personas: [
{nombre: "Genarito"},
{nombre: "Carlos"}
]
};
Suppose I want to change the name only of the first element, what is the best method and why, this is important for me since the project is big and I would like to use good practices whenever possible:
this.state.personas[0].nombre = "Otro nombre";
this.forceUpdate();
EITHER
this.state.personas[0].nombre = "Otro nombre";
this.setState(personas: this.state.personas);
Or would it be more verbose using auxiliary variables?
Any kind of help is welcome, thank you very much.
The way to do it according to the official documentation is through the
setState
. This example shows you how to do it as Hugo indicated.There are several ways to do it, the most optimal is if you are going to work with objects or json is to have an identifier for each value, something like this:
So when you want to make a change, you run a forEach going through the object and comparing the ids with the one you want to change, once you find it, you make the change, obviously for this, the ids must be unique, this is how databases work for example.