this.setState isn#39;t merging states as I would expect(this.setState 没有像我期望的那样合并状态)
问题描述
我有以下状态:
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()
:
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()
:
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 没有像我期望的那样合并状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:this.setState 没有像我期望的那样合并状态
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06