Immutable.Js - 在Map

时间:2017-05-10 21:58:38

标签: javascript json immutable.js

所以假设我做了一个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开始初始化这些属性?

3 个答案:

答案 0 :(得分:2)

您可以通过Immutable中的mergeDeep进行以下操作:

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"
        }
    }
}

希望这可以帮助您与我解决同一问题,我成功了!

答案 1 :(得分:1)

只是为了补充@ 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'});

答案 2 :(得分:0)

为了记录,你不需要做

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' }))