Problem:
Several children of a component have events that are triggered simultaneously. Each of these events is handled by style functions handleChangethat React immutability helpers use to combine complex objects into a state of a control component using something similar:
this.setState(React.addons.update(this.state, {$merge: new_value_object}));
This works great when events are fired independently, but when several events trigger a state update in this way, each one individually merges with the old version of the state. That is (psuedo code not intended to be executed).
function logState() { console.log(this.state) }
logState();
var next_value_object_A = {foo: '??'}
var next_value_object_B = {bar: '!!'}
this.setState(React.addons.update(this.state, {$merge: new_value_object_A}),
logState);
this.setState(React.addons.update(this.state, {$merge: new_value_object_B}),
logState);
Create
{foo: '??', bar: ''}
{foo: '', bar: '!!'}
A terrible solution that I do not want to use:
The following seems to work, but also seems like a serious anti-pattern;
setSynchronousState: function(nextState){
this.state = React.addons.update(this.state, {$merge: nextState});
this.setState(this.state);
}
. , , , .
:
getInitialState: function(){
this._synchronous_state =
return this._synchronous_state;
},
_synchronous_state: {},
setSynchronousState: function(nextState){
this._synchronous_state = React.addons.update(this._synchronous_state, {$merge: nextState});
this.setState(this._synchronous_state);
}
this.state, , . , this.state this._synchronous_state.
:
?