0

我想使用 ngrx 减速器更新我的状态,但我得到一个编译错误。

对于上下文。用户在表单上提交工作日志,我希望将此工作日志添加到状态的工作日志数组中。

这是我的状态的结构:

export declare interface Outreach {
  outreach: CaseState|null;
}

export declare interface CaseState {
  outreachCaseId: string;
  worklogs: WorklogCase[];  // <- I want to add the new worklog here
}

export declare interface WorklogCase {
  worklogId: string;
  username: string;
  details: string;
}

减速机:

const initialState: OutreachState = {
  outreach: null,
}

export const outreachDetailsReducers = createReducer<OutreachState>(
    initialState,
    on(outreachActions.addWoklogSuccess,
    state, {worklog}) => ({...state, worklogs: [...worklog]})),

我想我在减速器的最后一行有一些错误。有什么帮助吗?

4

1 回答 1

1

你有你的worklogs状态嵌套在一个outreach可能是的属性下null

因此,在使用 new更新其数组之前,您必须检查该outreach属性是否不是:nullworklogsworklog

export const outreachDetailsReducers = createReducer<OutreachState>(
  initialState,
  on(
    outreachActions.addWoklogSuccess,
    state, { worklog }) => ({
      ...state,
      outreach: state.outreach !== null
        ? {
            ...state.outreach,
            worklogs: [...state.outreach.worklogs, worklog]
          }
        : null,
      }
  )
),

理想情况下,您应该尝试使您的状态尽可能平坦,以避免嵌套带来的复杂性。

于 2021-12-07T10:17:30.773 回答