我最近开始研究Immutable.js,缺乏有用的例子非常令人沮丧。
我有一个深度嵌套的Immutable地图,其结构如下所示。我需要使用immutable.js来更新id为'264'的章节的页面数据。
var publisherData = {
"id": 367,
"publisher": {
"author": {
"id": 13,
"books": [
{
"id": 13,
"sections": [
{
"id": 49,
"chapters": [
{
"id": 262,
"pages": null
},
{
"id": 263,
"pages": null
},
{
"id": 264,
"pages":null
},
{
"id": 265,
"pages": {
"id": 159
},
}
]
},
{
"id": 50,
"chapters": [
{
"id": 266,
"pages": null
},
{
"id": 267,
"pages": null
},
{
"id": 268,
"pages": null
},
{
"id": 269,
"pages": null
},
{
"id": 270,
"pages": null
},
{
"id": 271,
"pages": null
},
{
"id": 272,
"pages": null
}
]
},
{
"id": 51,
"chapters": [
{
"id": 273,
"pages": null
}
]
},
{
"id": 52,
"chapters": [
{
"id": 277,
"pages": null
}
]
}
]
}
]
}
}
我设法使用此代码获取相关的moduleIndex和sectionIndex -
immutableStub.getIn(["publisher","author", "books"]).map((module,i) => {
return module.get('sections').map((section,j) => {
return section.get('chapters').map((chapter,k) => {
if(chapter.get('id') == '273'){
moduleIndex = i;
sectionIndex = j;
chapterIndex = k;
}
})
})
})
我该如何从这里开始?我不能使用'updateIn',因为keyPath只是部分延伸 - “publisher”,“author”,“books” - 然后它就是一个列表。
请提出解决方案。
答案 0 :(得分:1)
你差不多......
immutableStub.getIn([ "publisher", "author", "books" ]).map(( module, i ) => {
return module.get('sections').map(( section, j ) => {
return section.get('chapters').map(( chapter, k ) => {
if ( chapter.get('id') == '273' ) {
moduleIndex = i;
sectionIndex = j;
chapterIndex = k;
chapterToUpdate = chapter;
}
})
})
})
if ( chapterToUpdate ) {
// ...make changes to chapterToUpdate...
immutableStub = immutableStub.setIn([
"publisher",
"author",
"books",
moduleIndex,
"sections",
sectionIndex,
"chapters",
chapterIndex
], chapterToUpdate);
}