In ImmutableJS, how to push a new array into a Map?

ぐ巨炮叔叔 提交于 2019-12-03 10:30:22

You can do as follows: (see this JSBin)

const myMap = Immutable.fromJS({
  nested: {
    someKey: ['hello', 'world'],
  },
});

const myNewMap = myMap.updateIn(['nested', 'someKey'], arr => arr.push('bye'));

console.log(myNewMap.toJS());
// {
//  nested: {
//    someKey: ["hello", "world", "bye"]
//  }
// }

Since myMap is immutable, whenever you try to set/update/delete some data within it, it will return a reference to the new data. So, you would have to set it to a variable in order to access it (in this case, myNewMap).

If the array referenced at the key is a plain javascript array - then you will actually mutate that value - so your code will work as expected (ie - myMap will contain a mutable/mutated array at 'key' with the newData pushed in.) However, this kind of defeats the purpose of immutability so I would recommend that the key in myMap reference an Immutable.List. In which case you'll want to do:

var newMap = myMap.set('key', myMap.get('key').push(newData))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!