[英]Immutable.Js - Add new property in Map
So let's say that I make a REST API call and receive a JSON in this format: 因此,假设我进行REST API调用并以此格式接收JSON:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": null
}
}
And within in my reducer, make the JSON as an immutable as so: 在我的reducer中,将JSON设置为不可变的,如下所示:
Immutable.Map(Immutable.fromJS(action.json))
Along the way, is it possible to add properties under family
? 一路上,是否可以在
family
下添加属性?
For instance, when I am submitting a form to a server, ideally I like to send something like this: 例如,当我向服务器提交表单时,理想情况下我喜欢发送以下内容:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
Or do I have to initialized first to have those properties under family
from the start? 还是我先来的有以下这些属性来初始化
family
从一开始?
You can follow this way via mergeDeep
of Immutable : 您可以通过
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())
You will got this result 你会得到这个结果
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null,
"state": null
},
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
Hope this can help you for solving this same issue with me, I was succeed! 希望这可以帮助你解决同样的问题,我成功了!
Just to complement @julien-deniau answer. 只是为了补充@ julien-deniau的答案。 In case you have already properties in your object, you can use mergeIn .
如果对象中已有属性,则可以使用mergeIn 。 For example:
例如:
{
"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'});
For the record, you don't need to do 为了记录,您不需要这样做
const m = Immutable.Map(Immutable.fromJS(action.json))
But 但
const m = Immutable.fromJS(action.json)
does the job 做的工作
Then you can just do: 然后你可以这样做:
const n = m.setIn(['plan', 'family'], /* your family object */)
Here : 这里 :
const n = m.setIn(['plan', 'family'], Immutable.Map({ father: 'Homer', mother: 'Marge', son: 'Bartholomew' }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.