如果需要添加多个对象,如何使用ngrx更新状态?
例如,在下面的示例中,一个用户可以与多个任务相关联。
当前,当所有任务都返回时,存储将更新两次,并且每次更新时,最后一个任务将被新任务替换。这是预期的行为,但是您将如何初始化数组并捕获更新以将状态声明为对象数组并确保其保持同步?
task.reducer.ts
import * as TaskActions from './task.actions';
import { Action, createReducer, on } from '@ngrx/store';
import { ITask } from '../../models/task';
export interface State {
task: ITask | null;
error: any;
}
const initialState: ITask = {
basketTotal: 0,
carePlanPrice: 0,
category: null,
completionDate: null
};
export const taskReducer = createReducer(
initialState,
on(TaskActions.getData, state => ({ ...state })),
on(TaskActions.dataReceived, (state, payload) => ({ ...state, payload })),
on(TaskActions.dataNotReceived, state => ({ ...state })),
on(TaskActions.signOut, state => ({ ...state })),
on(TaskActions.signOutSuccess, state => ({ ...state, ...initialState })),
);
export function reducer(state: ITask | undefined, action: Action) {
return taskReducer(state, action);
}
task.effect.ts
@Effect()
getData$ = this.actions$.pipe(
ofType(TaskActions.getData),
switchMap(() => {
return this.afs.collection<ITask>('tasks', ref =>
ref.where('createdBy', '==', localStorage.getItem('uid'))).stateChanges().pipe(
);
}),
mergeMap(actions => actions),
map(action => {
if (action.payload) {
return TaskActions.dataReceived({ payload: TaskService.parseData(action.payload.doc.data()) });
} else {
return TaskActions.dataNotReceived();
}
})
);
task.actions.ts
import { createAction, props } from '@ngrx/store';
import { ITask } from '../../models/task';
export const getData = createAction('[Task] Get Data');
export const dataReceived = createAction('[Task] Data Received', props<{ payload: Partial<ITask> }>());
export const dataNotReceived = createAction('[Task] Data Not Received');
export const signOut = createAction('[Task] Sign Out');
export const signOutSuccess = createAction('[Task] Sign Out Success');
更新:
我尝试过
on(TaskActions.dataReceived, (state, payload) =>
({
...state,
tasks: [...state.tasks, payload.payload ]
})),
这是结果:
我希望有一个包含两个项目的数组:
task: [
{ ... }, { ... }
]
答案 0 :(得分:1)
spread语法还可用于数组以创建克隆。
on(TaskActions.dataReceived, (state, payload) =>
({
...state,
tasks: payload.condition ? [...state.tasks, payload.newTask ] : []
})),