如何使用CreateEffect处理多个Action分发?Ngrx新手求助
解决方案
方案1:创建合并型Action(推荐)
既然updateSubject和updatePoint属于同一提交动作的两个关联操作,最规范的方式是创建一个包含两个字段的新Action,只需一次dispatch即可完成操作,避免连续分发的问题:
// 定义合并后的新Action export const updateStudent = createAction( '[Student Update] Update subject and point', props<{subject: string; point: number}> () ); // 组件中仅需一次dispatch public onSubmit(){ this.store.dispatch( updateStudent({ subject: this.subject, point: this.point }) ); } // 在Reducer中同时处理两个字段的更新 export const studentReducer = createReducer( initialState, on(updateStudent, (state, { subject, point }) => ({ ...state, subject: subject, point: point })) );
方案2:用Effect触发第二个Action
如果必须保留两个独立Action,可以通过Effect监听第一个Action,自动分发第二个。需要注意将point通过Action payload传递,确保Effect能获取到参数:
// 修改updateSubject的payload,同时包含subject和point export const updateSubject = createAction( '[Student Update] Update subject', props<{subject: string; point: number}> () ); // 组件dispatch时传入完整参数 public onSubmit(){ this.store.dispatch( updateSubject({ subject: this.subject, point: this.point }) ); } // 编写Effect,监听updateSubject后分发updatePoint updateSubject$ = createEffect(() => this.actions$.pipe( ofType(updateSubject), map(action => updatePoint({ point: action.point })) ));
补充说明
连续dispatch两个Action并非绝对的"不良实践",但如果两个操作属于同一业务动作(比如提交学生信息),用单一Action更符合NgRx语义化动作、单一数据源的设计原则。若选择方案2,务必通过Action payload传递参数,避免直接依赖组件状态。
内容的提问来源于stack exchange,提问作者Curtis Lanz
相关产品推荐
相关产品推荐

