You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux reducer添加state项时,如何合并WEIGHT与GET_CODE数据到list同一对象

问题根源

你当前的两个reducer case都会直接往list数组末尾追加新对象,所以weight和code属性会被拆分到不同的数组元素中,才会出现你现在的结构。

按照你给出的触发顺序(先全量dispatch WEIGHT action,再dispatch GET_CODE action)、以及第一个空weight项不需要匹配code的规则,修改后的reducer逻辑如下:

case GET_CODE: {
  // 查找第一个weight非空且未赋值code的元素
  const targetIndex = state.list.findIndex(item => item.weight !== '' && !item.hasOwnProperty('code'))
  if (targetIndex === -1) {
    // 无匹配元素时的兜底逻辑,可按需调整为忽略/追加
    return {
      ...state,
      list: [...state.list, {code: action.payload.product.Code}]
    }
  }
  // 合并code到匹配的元素,不新增数组项
  const newList = [...state.list]
  newList[targetIndex] = {
    ...newList[targetIndex],
    code: action.payload.product.Code
  }
  return {
    ...state,
    list: newList
  }
}
case WEIGHT:
  return {
    ...state,
    list:[...state.list,{weight:action.payload}]
  }

效果验证

修改后运行逻辑完全符合你的预期:

  1. 三次WEIGHT action依次触发后,list结构为 [{weight: ''}, {weight: '100'}, {weight: '200'}]
  2. 两次GET_CODE action依次触发后,会分别将code 63、64合并到第二个、第三个元素中,最终得到你需要的结构

如果你的业务规则有调整(比如允许weight为空的项也需要匹配code),只需要修改findIndex的匹配规则即可。

内容的提问来源于stack exchange,提问作者Nedzny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:54:04