如何减少Redux中的嵌套数据?

时间:2015-11-27 09:05:02

标签: javascript redux

说我的状态是

{
taskGroups: [{
    id: 0,
    title: "Shopping list",
    list: [
        {id: 0, name: "Milk", done: false},
        {id: 1, name: "Eggs", done: true},
        {id: 2, name: "Bean bag", done: true}
    ]
},
    {
        id: 1,
        title: "Hit list",
        list: [
            {id: 0, name: "Vinoj", done: false},
            {id: 1, name: "Sandeep", done: true},
            {id: 2, name: "Amala", done: true},
            {id: 3, name: "Dixy", done: true},
            {id: 4, name: "Ajay", done: true},
            {id: 5, name: "Ashwin", done: true},
            {id: 6, name: "Yashin", done: true},
            {id: 7, name: "Mudassir", done: true},
            {id: 8, name: "Ishan", done: true}
        ]
    }
],
searchText: ""};

假设我想使用操作更新其中一个任务组列表中项目的名称:

 updateListItem(text, taskGroupId, listItemId){
    return { type: 'UPDATE_LIST_ITEM', text, taskGroupId, listItemId};
}

我的根减速器:

export function rootReducer(state = initialState, action) {
    switch (action.type) {

    case 'UPDATE_LIST_ITEM':
        return {
            taskGroups: state.taskGroups.map(taskGroup => {
                if (taskGroup.id === action.taskGroupId)
                    return {
                        ...taskGroup,
                        list: taskGroupListReducer(taskGroup.list, action)
                    };
                else  return taskGroup;
            }),
            searchText: state.searchText
        };
        //other cases
}

任务组列表缩减器:

function taskGroupListReducer(list = [], action) {
      case "UPDATE_LIST_ITEM":
        return list.map(item => {
            if (item.id === action.listItemId)
                return {...item, name: action.text};
            return item;
        });
    //other cases
}

这里我在列表数组中使用map。由于我实现搜索的方式,我不能使用列表项的索引,因为它会中断,否则我可以使用切片。 如果我不使用标准化数据(normalizr),如果不使用map(通过每个项目),如何实现这一目标呢?

0 个答案:

没有答案