So i\'ve been working on this for awhile and felt it would be best to refactor my code so that the state is set up as an array of objects. What i\'m trying to do is increme
Get current state, modify it and setState()
it:
var stateCopy = Object.assign({}, this.state);
stateCopy.items[key].upVotes += 1;
this.setState(stateCopy);
Note: This will mutate the state. Here's how to do it without mutation:
var stateCopy = Object.assign({}, this.state);
stateCopy.items = stateCopy.items.slice();
stateCopy.items[key] = Object.assign({}, stateCopy.items[key]);
stateCopy.items[key].upVotes += 1;
this.setState(stateCopy);
It's possible to directly edit the value on your array and set the state to the modified object, considering you're not using immutable.js, that is...
this.state.array[i].prop = 'newValue';
this.setState({ array: this.state.array });
The problem with direct editing is that React doesn't know the state changed and the update lifecycle doesn't fire. But setting the state again forces an update.
-- EDIT --
If state is Immutable...
const array = this.state.array.slice();
array[i].prop = 'newValue';
this.setState({ array });
-- EDIT 2 --
Thanks to the selected answer I realized this would still mutate the element since the array contains only references to the object in question. Here's a concise ES6-y way to do it.
const array = [...this.state.array];
array[i] = { ...array[i], prop: 'New Value' };
this.setState({ array });