我相信使用 Immutable 执行此操作的惯用方法是使用大量的.map
和.update
调用:
const state = fromJS(/*...*/);
const newState = state.update('departments',
departments => departments.map(
department => department.update('employees',
employees => employees.map(
employee => employee.update('projects',
projects => projects.map(
project => project.get('projectId') === 200 ?
project.set('projectName', 'NEW_PROJECT_NAME') :
project
))))));
const state = Immutable.fromJS({
departments: [{
departmentName: 'PHP',
employees: [{
employeeId: 1000,
employeeName: 'Manish',
projects: [{
projectId: 200,
projectName: 'ABC'
},
{
projectId: 300,
projectName: 'DEF'
}
]
}]
}]
})
const newState = state.update('departments',
departments => departments.map(
department => department.update('employees',
employees => employees.map(
employee => employee.update('projects',
projects => projects.map(
project => project.get('projectId') === 200 ?
project.set('projectName', 'NEW_PROJECT_NAME') :
project
))))));
console.log(newState);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>
处理深度嵌套的数据很烦人。我认为如果你稍微扁平化你的数据结构,你可以让你的生活变得更简单。以这个结构为例:
const state = fromJS({
departments: [{
employeeIds: [ 1000 ]
}],
employees: {
1000: {
employeeId: 1000,
employeeName: 'Manish',
projectIds: [ 200, 300 ]
}
},
projects: {
200: {
projectId: 200,
projectName: 'ABC'
},
300: {
projectId: 300,
projectName: 'DEF'
}
}
});
使用这样的结构,您原始问题的答案将像单个一样简单updateIn
:
const newState = state.updateId(['projects', 200],
project => project.set('projectName', 'NEW_PROJECT_NAME'));