【发布时间】:2016-01-15 19:57:56
【问题描述】:
我有一个深度嵌套的不可变结构,其中包含地图和列表。我不确定在结构中更新嵌套映射的最佳方法(id:356 的节点)。
我创建了一个搜索列表的函数,我找到了目标地图,我更新了它。但是结构完好无损!!知道我做错了什么吗?
https://jsbin.com/sadoni/1/edit?js,console
var structure = Immutable.fromJS(
{
someKey:{id:1},
links:[
{id:123, c:false, chd:[]},
{id:134, c:false, chd:[
{id:212, c:false, chd:[
{id:245, c:false, chd:[]},
{id:256, c:false, chd:[]}
]},
{id:145, c:false, chd:[]},
{id:156, c:false, chd:[]},
{id:213, c:false, chd:[
{id:313, c:false, chd:[]},
{id:314, c:false, chd:[
{id:345, c:false, chd:[]},
{id:356, c:false, chd:[]}
]}
]}
]}
]
}
);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - _findNode
function _findNode(nodes, func, cb){
let found = false;
var findInTree = (nodes, func) => {
if(nodes && nodes.size > 0){
nodes.forEach(node => {
if(found === false){
if (func(node) === true) {
found = true;
cb(node, nodes);
} else {
let chd = node.get('chd');
if(chd && chd.size > 0 && found === false){
findInTree(chd, func);
}
}
}
});
}
};
findInTree(nodes, func, cb);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - _filter function
function filter(link){ return link.get('id')===356; }
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - _find the links array inside the tree
var links = structure.get('links');
function changeTheNode(node, nodes){
console.log(nodes.get(1).toJS()); // log nodes array before the update
var index = nodes.findIndex(function(n){ return n === node; });
nodes = nodes.update(index, function(itm){ return itm.set('c', true); });
// nodes array changed
console.log(nodes.get(1).toJS());
// structure tree is still the same :(
//console.log(structure.toJS());
}
_findNode(links, filter, changeTheNode);
【问题讨论】:
标签: immutable.js