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

如何在Redux Toolkit中向嵌套在对象内的数组列表添加新对象

问题解决

你当前代码的问题是直接对state.vocabulary[step]做覆盖赋值,每次调用addWord都会把对应step下的单词数组替换为仅包含新单词的数组,自然无法实现追加效果。

Redux Toolkit 内部集成了 Immer 库,允许你在 reducer 中直接编写可变语法,内部会自动转换为符合规范的不可变更新,不需要手动写展开运算符。

修正后的addWord reducer 代码如下:

addWord: (
  state,
  action: PayloadAction<{ step: number; newWord: WordState }>,
) => {
  const { step, newWord } = action.payload;
  // 先判断对应step的数组是否存在,不存在则初始化空数组
  if (!state.vocabulary[step]) {
    state.vocabulary[step] = [];
  }
  // 直接往数组里追加新单词即可
  state.vocabulary[step].push(newWord);
},

如果你习惯保留类原生Redux的展开写法,RTK也完全兼容,写法如下:

state.vocabulary[step] = [...(state.vocabulary[step] || []), newWord];

两种写法都可以实现你预期的数组追加效果,符合你给出的最终状态结构要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:42:04