如何更新嵌套的immutable.js中的多个项目按键映射?

时间:2017-05-18 16:05:28

标签: javascript redux immutable.js

我正在使用REACT + REDUX并使用immutable.js 所以我在状态

中有这个结构
const jobs = Immutable.OrderedMap({
  job1: Immutable.Map({name: 'job1Name', guid: 123, status: 'in progress'}),
  job2: Immutable.Map({name: 'job2Name', guid: 432,  status: 'completed'}),
  job3: Immutable.Map({name: 'job3Name', guid: 555,  status: 'in progress'})
})

并且我在reducer中有这个有效载荷

const payload = Map({id: 'job1', status: 'completed'}, {id: 'job3', status: 'completed'});

如何获得此

const jobs = Immutable.OrderedMap({
  job1: Immutable.Map({name: 'job1Name', guid: 123, status: ' completed'}),
  job2: Immutable.Map({name: 'job2Name', guid: 432,  status: 'completed'}),
  job3: Immutable.Map({name: 'job3Name', guid: 555,  status: 'completed'})
})

我认为这与merge()mergeIn()有关,但我不确定

1 个答案:

答案 0 :(得分:0)

如果您只想更新status字段,那么类似的内容将起作用:

const jobs = Immutable.OrderedMap({
  job1: Immutable.Map({name: 'job1Name', guid: 123, status: 'in progress'}),
  job2: Immutable.Map({name: 'job2Name', guid: 432, status: 'completed'}),
  job3: Immutable.Map({name: 'job3Name', guid: 555, status: 'in progress'})
})
const payload = Immutable.List([
  {id: 'job1', status: 'completed'}, 
  {id: 'job3', status: 'completed'}
]);

const reducer = (state, payload) => 
  payload.reduce((memo, {id, status}) => memo.update(id, j => j.set("status", status)), state);

console.log(reducer(jobs, payload).toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

PS:我已将Map替换为Immutable.List payload,因为我无法识别您Map用法的语法