How can I achieve the following using ImmutableJS:
myMap.get(key).push(newData);
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))
来源:https://stackoverflow.com/questions/31648907/in-immutablejs-how-to-push-a-new-array-into-a-map