You should not mutate state. Instead create a new object without modifying the previous one.
prevState[name] = value;
return { ...prevState };
The above first mutates the previous state, then returns a copy of it. Instead return a copy that contains the new value without modifying the previous state.
return { ...prevState, [name]: value };
The above copies the previous state and adds or overrides the (evaluated) name
property with value
. This is all done without mutating prevState
.
Applying this to your actual code you would get the following.
setFieldsToEdit((prevState) => {
const { name, value } = event.target;
if (name == "fecha_presentacion") {
return { ...prevState, [name]: Number(value) };
} else {
return { ...prevState, [name]: value };
}
});
// or (depending on preference)
setFieldsToEdit((prevState) => {
let { name, value } = event.target;
if (name == "fecha_presentacion") value = Number(value);
return { ...prevState, [name]: value };
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…