Ngrx:无法分配为只读对象“ [Object]”的属性“ Property”

时间:2019-08-21 11:51:50

标签: javascript angular typescript javascript-objects ngrx

我正在使用ngrx存储。

在我的状态下,我必须物品

export interface ISchedulesState {
  schedulings: ISchedules;
  actualTrips: ISchedule[];
}

这是我的界面

export interface ISchedules {
  [key: string]: ISchedule[];
}

export interface ISchedule {
  dest: number;
  data: string
}

在减速器中,我更新actualTrips

export const SchedulingReducers = (
  state = initialSchedulingState,
  action: SchedulesAction
): ISchedulesState => {
  switch (action.type) {
    case ESchedulesActions.GetSchedulesByDate: {
      return {
        ...state
      };
    }
    case ESchedulesActions.GetSchedulesByDateSuccess: {
      return {
        ...state,
        schedulings: action.payload
      };
    }
    case ESchedulesActions.GetSchedulesByTime: {
      let time = action.payload;
      state.actualTrips = [...(state.schedulings[time] || [])]; // if not data return empty array
      return state;
    }
    default:
      return state;
  }
};

但实际上我得到一个错误

  

错误TypeError:无法分配为只读对象'[object Object]'的属性'actualTrips'

3 个答案:

答案 0 :(得分:6)

Redux模式的基本原理是状态及其部分的不变性,因为它让我们仅通过对象引用而不是比较整个对象来检测更改。

在化简器中,您不能直接分配状态属性(state.actualTrips =),因为变更检测器(和选择器)不会将其检测为变更。

要修改状态,请返回带有新修改的状态副本。

  const time = action.payload;
  return {
      ...state,
      actualTrips: [...(state.schedulings[time] || [])]
  }

答案 1 :(得分:4)

如果你想改变 state.actualTrips = myNewValue 是不允许的,因为有一个严格的设置。所以一种方法可能是 clonedeep 并返回对象,比如 newState = cloneOfState ... 我没有测试它。所以我在 app.module 中为 Store 更改了设置。 我的示例:将 strictStateImmutability 更改为 false(此处为完整文档:https://ngrx.io/guide/store/configuration/runtime-checks

    StoreModule.forRoot(ROOT_REDUCERS_TOKEN, {
        metaReducers,
        runtimeChecks: {
            // strictStateImmutability and strictActionImmutability are enabled by default
            strictStateSerializability: true,
            strictActionSerializability: true,
            strictActionWithinNgZone: true,
            strictActionTypeUniqueness: true,
            // if you want to change complexe objects and that we have. We need to disable these settings
            // change strictStateImmutability, strictActionImmutability
            strictStateImmutability: false, // set this to false
            strictActionImmutability: true,
        },
    }),

答案 2 :(得分:1)

当我更改模板中的输入值时发生了该错误。我使用的是 Angular11 + NGRX11,所以我知道我从 store 更改了一个值,这是我的修复:

之前:

 this.store.dispatch(new Actions.LoginUser({ user: this.user }));

之后:

 const clone = { 
  user: Object.assign({}, this.user) 
 };
 this.store.dispatch(new Actions.LoginUser(clone));
相关问题