首页 > 解决方案 > 如何使用 Immutable.js 在嵌套 Map 中添加新的键/值对

问题描述

我想向嵌套在另一个 Map 中的 Map 添加一个新的键/值对。如果密钥已经存在,它应该被替换。

我认为mergeDeepIn()应该可以解决问题,但我得到一个“无效的 keyPath”错误。

状态如下所示:

{
   "requests":{
      "1":{
         "title":"I have a question",
         "customerId":2,
         "messages":{
            "222":{
               "text":"Hello!",
               "senderId":1,
            },
         },
        ...
      },
      ...
   },
}

'requests' 和 'messages' 是不可变的 Maps。

我试过这个:

const message = fromJS({
  "5": {
    text: "test",
  },
})
state.mergeDeepIn(['requests', 1, 'messages'], message)

该消息应添加到“消息”地图中。

标签: javascriptreactjsreact-reduximmutable.js

解决方案


Immutability is a property of a data structure and means: After that data structure is created it will never ever change again. Adding or replacing a value from/to a Map means mutating the Map, which is exactly what immutable-js tries to prevent.

What you can do is create a new Map from your already existing one.

const {Map} = require('immutable');
m = Map({a:1});

Map({...m.toJSON(), b:2}) // Map { "a": 1, "b": 2 }
Map({...m.toJSON(), a:2}) // Map { "a": 2 }
m.set('a', 2) // Map { "a": 2 } , creates a new map same as line above

推荐阅读