![](/img/trans.png)
[英]NGRX Store. Cannot assign to read only property '18' of object '[object Array]'
[英]Ngrx : Cannot assign to read only property 'Property' of object '[Object]'
我正在使用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;
}
};
但實際上我得到一個錯誤
錯誤類型錯誤:無法分配給對象“[object Object]”的只讀屬性“actualTrips”
Redux 模式的基本原則是狀態及其部分的不變性,因為它讓我們只通過對象引用來檢測變化,而不是比較整個對象。
在您的減速器中,您不能直接分配狀態屬性( state.actualTrips =
),因為更改檢測器(和選擇器)不會將其檢測為已更改。
要修改狀態,請返回帶有新修改的狀態副本。
const time = action.payload;
return {
...state,
actualTrips: [...(state.schedulings[time] || [])]
}
如果要更改 state.actualTrips = myNewValue 是不允許的,因為有一個嚴格的設置。 所以一種方法是可以克隆深度並返回對象,比如 newState = cloneOfState... 我沒有測試它。 所以我改變了商店的 app.module 中的設置。 我的示例:將 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,
},
}),
當我更改模板中的輸入值時,我發生了這個錯誤。 我正在使用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));
我在https://stackoverflow.com/a/58279719找到了答案
只需將狀態復制到新對象中
const oldState = getState();
let state = JSON.parse(JSON.stringify(oldState)); // here
state.propertyToChange = "newValue";
patchState({
...state
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.