如何为Ngrx Store应用中动态新增的坐席对象设置统一初始状态
实现方案
- 第一步:抽离单个坐席的通用初始状态
把每个坐席共用的初始结构抽为独立常量,后续所有新增坐席都复用这个常量避免重复代码:
// 单个坐席的通用初始状态模板 const INITIAL_AGENT_CUSTOMER_STATE = { customer: [], cursors: { after: "", before: "", hasNext: false, hasPrevious: false, }, total: 0, loading: false, errorMessage: null, items_per_page: 2, pageSizeOptions: [2, 3, 5, 10, 15], pageIndex: 0, searchKey: "", };
- 第二步:调整根初始状态配置
初始状态下不需要预填任何固定ID的坐席数据,直接设置为空对象即可:
export const initialState: State = { agent_customer: {} };
- 第三步:在Reducer中新增自动初始化逻辑
有两种常用实现方式,可根据业务需求选择:
方案1:单独定义新增坐席状态的Action,需要新增时主动触发
先定义Action:
然后在Reducer中处理这个Action:import { createAction, props } from '@ngrx/store'; export const addAgentCustomerState = createAction( '[Agent Customer] Add Agent State', props<{ agentId: number }>() );
方案2:在加载坐席数据的逻辑中隐式初始化,无需额外触发Actionimport { createReducer, on } from '@ngrx/store'; export const agentCustomerReducer = createReducer( initialState, on(addAgentCustomerState, (state, { agentId }) => { // 已存在对应ID的状态则直接返回,避免覆盖已有数据 if (state.agent_customer[agentId]) return state; // 不可变更新新增坐席状态 return { ...state, agent_customer: { ...state.agent_customer, [agentId]: { ...INITIAL_AGENT_CUSTOMER_STATE } } }; }) );
如果你不需要单独触发新增操作,而是在加载某个坐席的客户数据时自动初始化,可直接在加载相关的Reducer逻辑中加判断:// 示例:处理加载坐席客户列表的Action on(loadAgentCustomers, (state, { agentId }) => { // 不存在对应ID的状态时,先套用初始模板 const agentState = state.agent_customer[agentId] ?? { ...INITIAL_AGENT_CUSTOMER_STATE }; return { ...state, agent_customer: { ...state.agent_customer, [agentId]: { ...agentState, loading: true // 同步修改加载状态 } } }; })
两种方案都可以保证任意ID的坐席新增到Store时,都会自动套用预设的统一初始结构,不需要提前写死ID配置。
内容的提问来源于stack exchange,提问作者walexy
相关产品推荐
相关产品推荐

