问题:
组件的多个子节点同时触发事件.这些事件中的每一个都由handleChange样式函数处理,这些函数使用React的不变性助手将复杂对象合并到控制组件的状态中,类似于;
this.setState(React.addons.update(this.state, {$merge: new_value_object}));
Run Code Online (Sandbox Code Playgroud)
当事件独立触发时,这可以正常工作,但是当多个事件以这种方式导致状态更新时,每个事件都是从旧版本的状态单独合并.即(伪代码,不打算执行).
function logState() { console.log(this.state) }
logState(); // {foo: '', bar: ''}
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);
Run Code Online (Sandbox Code Playgroud)
会生产;
{foo: '??', bar: ''}
{foo: '', bar: '!!'}
Run Code Online (Sandbox Code Playgroud)
我不想使用的可怕解决方案:
以下似乎有效,但似乎也是一个主要的反模式;
setSynchronousState: function(nextState){
this.state = React.addons.update(this.state, {$merge: nextState});
this.setState(this.state);
}
Run Code Online (Sandbox Code Playgroud)
这依赖于直接修改国家.我没有看到运行此代码时出现任何直接问题,它确实解决了手头的问题,但我不得不想象我会继承这个解决方案的一些大量技术债务.
这个解决方案的稍微好一点的版本是;
getInitialState: function(){
this._synchronous_state = //Something
return this._synchronous_state;
},
_synchronous_state: {},
setSynchronousState: function(nextState){
this._synchronous_state = React.addons.update(this._synchronous_state, {$merge: nextState}); …Run Code Online (Sandbox Code Playgroud)