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

☆樱花仙子☆ 提交于 2019-11-27 17:50:28

问题


How can I achieve the following using ImmutableJS:

myMap.get(key).push(newData);


回答1:


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).




回答2:


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))


来源:https://stackoverflow.com/questions/31648907/in-immutablejs-how-to-push-a-new-array-into-a-map

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