ImmutableJS - 处理对象列表?
ImmutableJS - Dealing with list of objects?
我正在学习使用 ImmutableJS,但我有点困惑。我查看了文档,发现有用于对象的映射和用于数组的列表。
所以我构建了一个像这样的对象:
sampleTodo = Immutable.Map({text: 'Testing 1 2 3', status: 'Open'})
然后做:list = Immutable.List().push(sampleTodo)
不确定这是否正确。如果是这样,当我有一个索引并且必须 return 修改后的 List
.
时,我会卡住
比如index为0,我做:
list.get(index)
并得到
Object {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
因此,我看不出如何通过 List
.
将 Map
对象的状态设置为 status: "Complete"
我在这里找到了一个可行的解决方案:
list = list.update(
list.findIndex(function(item) {
return item.get("name") === "third";
}), function(item) {
return item.set("count", 4);
}
);
或者,就我而言:
list = list.update(
index, function(todo) {
return todo.set('status', 'Complete');
}
);
你可以这样做:
list = list.setIn([index, 'status'], 'Complete')
要理解的关键点是 .setIn
使用任何底层数据类型的索引。由于 list
是 Immutable.List
,我们可以使用整数来查找第一个元素,即 Immutable.Map
。 Immutable.Map
的 "index" 是对象 key
(string),这就是为什么你也可以做
list = list.getIn([index, 'status'])
获取项目的状态。
我正在学习使用 ImmutableJS,但我有点困惑。我查看了文档,发现有用于对象的映射和用于数组的列表。
所以我构建了一个像这样的对象:
sampleTodo = Immutable.Map({text: 'Testing 1 2 3', status: 'Open'})
然后做:list = Immutable.List().push(sampleTodo)
不确定这是否正确。如果是这样,当我有一个索引并且必须 return 修改后的 List
.
比如index为0,我做:
list.get(index)
并得到
Object {size: 1, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
因此,我看不出如何通过 List
.
Map
对象的状态设置为 status: "Complete"
我在这里找到了一个可行的解决方案:
list = list.update(
list.findIndex(function(item) {
return item.get("name") === "third";
}), function(item) {
return item.set("count", 4);
}
);
或者,就我而言:
list = list.update(
index, function(todo) {
return todo.set('status', 'Complete');
}
);
你可以这样做:
list = list.setIn([index, 'status'], 'Complete')
要理解的关键点是 .setIn
使用任何底层数据类型的索引。由于 list
是 Immutable.List
,我们可以使用整数来查找第一个元素,即 Immutable.Map
。 Immutable.Map
的 "index" 是对象 key
(string),这就是为什么你也可以做
list = list.getIn([index, 'status'])
获取项目的状态。