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

如何在Redux的EntityAdapter中更新嵌套结构的对象数据

Redux createEntityAdapter嵌套状态更新方案

核心思路

createEntityAdapter的updateOne方法的changes配置仅支持和原实体做浅合并,嵌套结构的变更需要你先构造出完整的修改后子结构,再传入changes字段。

实现代码(以cheese的Qty加1为例)

方案1:使用updateOne标准写法

const targetEntity = state.entities[id];
if (targetEntity) {
  // 遍历生成更新后的ingredients数组
  const newIngredients = targetEntity.burger.ingredients.map(item => {
    // 匹配到cheese项时更新Qty,其余项保持不变
    if (item.title === 'cheese') {
      return { ...item, Qty: item.Qty + 1 };
    }
    return item;
  });
  // 执行更新
  burgerAdapter.updateOne(state, {
    id,
    changes: {
      burger: {
        ...targetEntity.burger, // 保留burger下其他字段不变
        ingredients: newIngredients
      }
    }
  });
}

方案2:利用Immer可变写法(更简洁)

因为createSlice内置了Immer支持,你可以直接修改状态字段,不需要手动构造不可变更新:

const targetEntity = state.entities[id];
if (targetEntity) {
  const cheeseItem = targetEntity.burger.ingredients.find(item => item.title === 'cheese');
  if (cheeseItem) {
    cheeseItem.Qty += 1;
  }
}

注意事项

  • 方案1中用map生成新数组、返回新对象的写法是为了保证不可变更新,如果你用方案2的Immer写法则不需要关心这个问题。
  • 操作前加判断避免实体不存在时报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:45:03