One of the basic ideas of React is that state changes should always and only occur via this.setState(...) and not manipulate the state manually. But for the case of a state being an deep array, so an array of object literals (some JSON data really), updating that State becomes really expensive. If I only want to update one element of such an array, the code would be something like the following.
handleChange(index, newElement){
var newStateArray = _.cloneDeep(this.state.myArray);
newStateArray[index] = newElement;
this.setState({myArray: newStateArray });
}
I know the standard solution would be using shallow copying, but that only really is a copy for shallow arrays. In my case it is not, so shallow copying would be "wrong" in a react sense as it would change the state. So really how is one supposed to handle this? I can just use a shallow copy and it works, but it feels dirty and is technically wrong.
edit: Or to clarify: Is there anything bad that could happen if I would just use the shallow copy thing and to be sure tell React to update manually?
edit: Oh this seems to have solved itself. Shallow copying doesn't work as I thought it would. I'm new to JS, pardon. For reference:
var a = [{a:1}, {b:2}, {c:3}]
var b = a.slice();
b[0] = 42; // I thought this would change a, but it doesn't!
b[0]=42will not changea(becauseaandbare separate arrays),b[0].a=42will changea, because the object which lives inb[0]is the same one which lives ina[0](same forb[1]=a[1], etc.). That's what a shallow copy is all about. See my answer for how to handle this situation safely.