我正在尝试编写一个函数来更新我拥有的不可变对象。我正在使用return myitem.updateIn
,所以我可以链接另一个已经正常工作的更新。到目前为止,我有这个:
memo.updateIn(['Topics', 'filters'], function(topic) {
topic.map(function(singleTopic) {
singleTopic.update('filters', function(subTopicFilters) {
subTopicFilters.map(function(singleSubTopic) {
if(singleSubTopic.get('checked')){
console.log("check", singleTopic.toJS());
return singleTopic.set('checked', true);
}
})
})
})
});
控制台日志里面正在击中正确的部分,但是这似乎并没有像我想象的那样更新不可变的地图。 checked
中的psycological disorders
值应设置为true。请参阅此处的小提琴,例如https://jsfiddle.net/alexjm/c5edxaue/27/。
对于某些上下文,这将在返回中使用,其中将按顺序在备忘录上运行几个单独的.update
returnModifiedData(memo) {
return memo.update (....
).update( .....
.update();
此功能是此过程的第一步,其他2个功能已经正常工作。我不确定我做错了什么不能正确更新,可能我是如何尝试.set
内部单音?基本逻辑是检查主题是否包含内部检查的子主题,如果是,请检查主题。任何帮助将不胜感激。谢谢!
编辑:忘记添加备忘录本身的内容:
const memo = {
"Topics": {
"filters": {
"Psychological disorders": {
"checked": false,
"filters": {
"Anxiety disorders": {
"filters": {},
"checked": true
}
}
},
"test": {
"checked": false,
"filters": {
"test": {
"filters": {},
"checked": false
}
}
}
},
"isOpen": false
}
};
答案 0 :(得分:1)
如果你能解释一下你想要实现的逻辑,那就更好了。
我猜这里:
迭代并更新Topics->filters
中的项目。
对于每个singleTopic
次迭代,进一步遍历它filters
。
如果singleSubTopic
中的任何checked
true
为singleTopic
,请将checked
的{{1}}更新为true
以下是您的期望:
const map = {
"Topics": {
"filters": {
"Psychological disorders": {
"checked": false,
"filters": {
"Anxiety disorders": {
"filters": {},
"checked": true
}
}
},
"test": {
"checked": false,
"filters": {
"test": {
"filters": {},
"checked": false
}
}
}
},
"isOpen": false
}
};
let memo = Immutable.fromJS(map);
memo = memo.updateIn(['Topics', 'filters'], function(topics) {
// Remember to return the updated topics.
return topics.map(function(singleTopic) {
// If singleTopic has any of its singleSubTopic under filters have value checked=== true
// update the singleTopic's checked, otherwise return unaltered.
if (singleTopic.get('filters').some(function(singleSubTopic) {
return singleSubTopic.get('checked');
})) {
return singleTopic.set('checked', true);
}
return singleTopic;
});
});
console.log(memo.toJS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>