不可变JS - 在嵌套在Map中的列表中添加/删除

时间:2017-03-03 10:59:07

标签: redux immutable.js

使用redux appilcation我有以下数据结构,使用fromJS()

将其转换为不可变对象
import { Map, push, fromJS } from 'immutable';

const initialState = fromJS({
filter: "cards",
contacts: [
    {
        name: "Someone 1",
        email: "someone@example.com",
        phone: "+1 900 78601",
        location: "Los Angeles"
    },
]});

我的减速机看起来像这样:

function contactsReducer(state = initialState, action) {
switch (action.type) {
    case ADD_CONTACT:
        return state.get('contacts').push(Map(
          {
              name: "Someone 1",
              email: "someone@example.com",
              phone: "+1 900 78601",
              location: "Los Angeles"
          }
        ));
    default:
        return state;
}}

我无法弄清楚如何定位联系人数组并为其添加更多联系人。我写的reducer修改了新状态的整个结构。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

您可以使用地图上的set在您调用contacts后使用新更新的列表更新push字段。

state.set('contacts').push(Map(
     {
        name: "Someone 1",
        email: "someone@example.com",
        phone: "+1 900 78601",
        location: "Los Angeles"
     }
 ))

答案 1 :(得分:0)

我根据Alex Parij给出的答案找到了答案,需要稍作修改。这是:

state.set('contacts', state.get('contacts').push(Map(
          {
            name: "Someone 1",
            email: "someone@example.com",
            phone: "+1 900 78601",
            location: "Los Angeles"
          }
)))