[英]Immutable.Js - Add new property in Map
因此,假设我进行REST API调用并以此格式接收JSON:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": null
}
}
在我的reducer中,将JSON设置为不可变的,如下所示:
Immutable.Map(Immutable.fromJS(action.json))
一路上,是否可以在family
下添加属性?
例如,当我向服务器提交表单时,理想情况下我喜欢发送以下内容:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
还是我先来的有以下这些属性来初始化family
从一开始?
您可以通过mergeDeep
of Immutable遵循这种方式:
const { fromJS } = require('immutable@4.0.0-rc.9')
const initialState = fromJS({
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null,
"state": null
},
"family": null
}
})
const newState = initialState.mergeDeep({
"plan": {
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
})
console.log(newState.toJS())
你会得到这个结果
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null,
"state": null
},
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
希望这可以帮助你解决同样的问题,我成功了!
只是为了补充@ julien-deniau的答案。 如果对象中已有属性,则可以使用mergeIn 。 例如:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
---> you need to add smthg here
}
}
}
state.mergeIn([
'plan',
'family'], {grandfather:'Abraham Jedediah'});
为了记录,您不需要这样做
const m = Immutable.Map(Immutable.fromJS(action.json))
但
const m = Immutable.fromJS(action.json)
做的工作
然后你可以这样做:
const n = m.setIn(['plan', 'family'], /* your family object */)
这里 :
const n = m.setIn(['plan', 'family'], Immutable.Map({ father: 'Homer', mother: 'Marge', son: 'Bartholomew' }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.