问题
I'm using ngrx store.
In my state I have to items
export interface ISchedulesState {
schedulings: ISchedules;
actualTrips: ISchedule[];
}
Here are my interfaces
export interface ISchedules {
[key: string]: ISchedule[];
}
export interface ISchedule {
dest: number;
data: string
}
In reducer I update 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;
}
};
But actually I get an error
ERROR TypeError: Cannot assign to read only property 'actualTrips' of object '[object Object]'
回答1:
The basic principle of Redux pattern is immutability of state and its parts, because it let's us to detect changes just by object reference instead of comparing whole objects.
In your reducer, you cannot directly assign a property of state (state.actualTrips =
), because change detector (and selectors) would not detect it as changed.
To modify state, you return a copy of the state with new modifications.
const time = action.payload;
return {
...state,
actualTrips: [...(state.schedulings[time] || [])]
}
来源:https://stackoverflow.com/questions/57591012/ngrx-cannot-assign-to-read-only-property-property-of-object-object