this.setState没有像我期望的那样合并状态 [英] this.setState isn't merging states as I would expect
问题描述
我有以下状态:
this.setState({ selected: { id: 1, name: 'Foobar' } });
然后我更新状态:
this.setState({ selected: { name: 'Barfoo' }});
由于setState要合并,我希望它是:
Since setState is suppose to merge I would expect it to be:
{ selected: { id: 1, name: 'Barfoo' } };
但它会吃掉ID而状态是:
But instead it eats the id and the state is:
{ selected: { name: 'Barfoo' } };
这是预期的行为以及只更新嵌套状态对象的一个属性的解决方案是什么?
Is this expected behavior and what's the solution to update only one property of a nested state object?
推荐答案
我认为 setState()
不进行递归合并。
I think setState()
doesn't do recursive merge.
您可以使用当前状态值 this.state.selected
构建新状态,然后调用 setState()
on:
You can use the value of the current state this.state.selected
to construct a new state and then call setState()
on that:
var newSelected = _.extend({}, this.state.selected);
newSelected.name = 'Barfoo';
this.setState({ selected: newSelected });
我用过函数 _.extend()
函数(来自underscore.js库)这里通过创建一个浅表副本来阻止修改现有的选定的
部分状态。
I've used function _.extend()
function (from underscore.js library) here to prevent modification to the existing selected
part of the state by creating a shallow copy of it.
另一种解决方案是编写 setStateRecursively()
,它在新状态下进行递归合并,然后调用 replaceState()
with it:
Another solution would be to write setStateRecursively()
which does recursive merge on a new state and then calls replaceState()
with it:
setStateRecursively: function(stateUpdate, callback) {
var newState = mergeStateRecursively(this.state, stateUpdate);
this.replaceState(newState, callback);
}
这篇关于this.setState没有像我期望的那样合并状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!