javascript - 如何使用 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)
该消息应添加到“消息”地图中。
解决方案
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
推荐阅读
- node.js - Google reCAPTCHA 无法在 Electron BrowserWindow 中解决
- git - git clone:我收到一个奇怪的身份验证错误
- amazon-ec2 - 如何使用 terraform 将 aws ec2 私有 ips 传递给模板文件
- javascript - jquery中输入类型文件的前缀“application /”是什么?
- python - Python Elif Flowdown 值选择器 - 如何限制值并防止错误?
- python - Pandas 用 df.apply 结果替换原始列空值
- reactjs - React.Children.only 期望接收单个 React 元素子状态数组 NextJS
- json - 如何在 jmeter 中使用正则表达式获取值
- r - 在R中用ggplot修改饼图的大小
- geojson - Mapbox gl 从 geojson 外部文件过滤