问题
I want to update value of one object only but updating value of one Object, Updates the value for all objects.
let default = {
name: '',
age: ''
}
this.state = {
values: Array(2).fill(default)
}
updateName (event) {
let index = event.target.id,
values = this.state.values;
values[index].name = event.target.value;
this.setState ({
values: values
});
}
回答1:
There are four significant problems in that code.
You're using the same object for all entries in your array. If you want to have different objects, you have to create multiple copies of the default.
You're calling
setStateincorrectly. Any time you're setting state based on existing state (and you're settingvaluesbased, indirectly, onthis.state.values), you must use the function callback version ofsetState. More: State Updates May Be AsynchronousYou can't directly modify the object held in
this.state.values; instead, you must make a copy of the object and modify that. More: Do Not Modify State Directlydefaultis a keyword (even though it's not currently used), you can't use it as an identifier. Let's usedefaultValueinstead.
Here's one way you can address all three (see comments):
// #4 - `default` is a keyword
let defaultValue = {
name: '',
age: ''
};
this.state = {
// #1 - copy default, don't use it directly
values: [
Object.assign({}, defaultValue),
Object.assign({}, defaultValue)
] // <=== Side note - no ; here!
}
updateName (event) {
let index = event.target.id,
// #2 - state updates working from current state MUST use
// the function callback version of setState
this.setState(prevState => {
// #3 - don't modify state directly - copy the array...
values = prevState.values.slice();
// ...and the object, doing the update
values[index] = {...values[index], name: event.target.value};
return {values};
});
}
Note that this line in the above:
values[index] = {...values[index], name: event.target.value};
...uses syntax from this JavaScript enhancement proposal, currently at Stage 4 (it will be in the ES2018 snapshot spec) and commonly enabled in React build environments.
回答2:
I would use the Array.prototype.map function with combination of the object spread syntax (stage 4):
Note that i changed the name of the default object to obj.default is a reserved key word in javascript
let obj = {
name: '',
age: ''
}
this.state = {
values: Array(2).fill(obj)
}
updateName(event){
const {id, value} = event.target;
this.setState(prev => {
const {values} = prev;
const nextState = values.map((o,idx) => {
if(idx !== id)
return o; // not our object, return as is
return{
...o,
name: value;
}
});
return{
values: nextState
}
});
}
来源:https://stackoverflow.com/questions/48700113/how-to-update-array-of-objects-in-react-js-using-state