更新 Angular / ngrx 减速器中的嵌套状态结构

Ell*_*iot 5 typescript redux ngrx angular

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

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

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

export class TimeEntry {
    cellIndex: number;
    hours: number;
    ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个减速器试图更新表格中单个单元格的小时数,但我在让它工作时遇到了一些问题。对于以下操作案例,状态保持不变:

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
                            }
                        })
                    }
                }
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

Ell*_*iot 3

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

尽可能避免嵌套状态的又一个原因是,随着减速器变得更长、更复杂。最终使用此Redux 资源来了解如何正确更新嵌套对象。

新代码:

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
                    }
                })
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)