更新Angular / ngrx reducer

时间:2018-04-07 00:07:43

标签: angular typescript redux ngrx

我有一个嵌套的状态结构,代表一个时间输入表。我存储了一个TimeEntryRow个对象数组,其中每个行对象都有自己的TimeEntry个对象数组。请注意,对象存储一个索引,表示它们在表中的位置。

export interface TimeState {
    timeEntryRows?: TimeEntryRow[];
    ...
}

export class TimeEntryRow {
    rowIndex: number;
    timeEntries: TimeEntry[];
    ...
}

export class TimeEntry {
    cellIndex: number;
    hours: number;
    ...
}

我有一个试图更新表中单个单元格的小时数的reducer,但是我遇到了一些问题。通过以下操作案例,状态保持不变:

case timeEntryActions.HOURS_CHANGED_ACTION: {
    return {
        ...state,
        timeEntryRows: {
            ...state.timeEntryRows.map(row => {
                return row.rowIndex !== action.payload.rowIndex ? row : {
                    ...row,
                    timeEntries: {
                        ...row.timeEntries.map(te => {
                            return te.cellIndex !== action.payload.cellIndex ? te : {
                                ...te,
                                hours: action.payload.hours
                            }
                        })
                    }
                }
            })
        }
    }
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

看起来我不小心将数组属性timeEntryRowstimeEntries设置为对象,而不是数组。

尽可能避免嵌套状态的另一个原因是,减速器变得越来越复杂。使用此Redux resource结束了如何正确更新嵌套对象。

新代码:

case timeEntryActions.HOURS_CHANGED_ACTION: {
    return {
        ...state,
        timeEntryRows: state.timeEntryRows.map(row => {
            return row.rowIndex !== action.payload.rowIndex ? row : {
                ...row,
                timeEntries: row.timeEntries.map(te => {
                    return te.cellIndex !== action.payload.cellIndex ? te : {
                        ...te,
                        hours: action.payload.hours
                    }
                })
            }
        })
    }
}