如何使用NgRx更新状态对象中的特定属性offerPrice并保留其他值?
Redux Reducer更新offerPrice属性的正确写法
问题分析
你当前的reducer代码存在对象展开层级错误,直接导致状态结构混乱,这是Redux工具显示异常的核心原因:
- 更新
offerDetails时错误展开了整个state,导致offerDetails中混入了根状态的所有属性 singleOfferDetails的赋值逻辑完全错误,错误地将state.offerPrice和action.payload拼成数组,完全偏离了预期的状态结构
正确代码示例
假设你的状态结构为嵌套对象(如state.offerDetails.singleOfferDetails.offerPrice),要更新offerPrice同时保留其他所有状态值,需逐层展开对应层级的对象:
case OffersActionTypes.SET_TOTAL_OFFER_PRICE: return { ...state, // 保留根状态的所有其他属性 offerDetails: { ...state.offerDetails, // 保留offerDetails下的其他属性 singleOfferDetails: { ...state.offerDetails.singleOfferDetails, // 保留singleOfferDetails下的其他属性 offerPrice: [...state.offerDetails.singleOfferDetails.offerPrice, action.payload] // 追加新的offerPrice值,若要直接替换则改为action.payload } } }
关键注意事项
- 每次嵌套更新必须逐层展开父级对象,确保只有目标属性被修改,其余属性通过对象/数组展开语法保留
- 如果
offerPrice是单个值而非数组,直接将offerPrice赋值为action.payload即可,无需数组展开 - 如果
singleOfferDetails是数组(需更新数组中某元素的offerPrice),则需要先定位目标元素,通过数组映射+元素展开的方式处理,示例如下(假设按索引更新):
case OffersActionTypes.SET_TOTAL_OFFER_PRICE: const targetIndex = 0; // 替换为实际要更新的元素索引 return { ...state, offerDetails: { ...state.offerDetails, singleOfferDetails: state.offerDetails.singleOfferDetails.map((item, index) => index === targetIndex ? {...item, offerPrice: action.payload} : item ) } }
内容的提问来源于stack exchange,提问作者nhoyti
相关产品推荐
相关产品推荐

