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

Redux InitialState从数组改为对象后运行报错问题排查

问题根因

你修改Redux state为对象结构后,reducer的两个action分支违反了Redux的state结构不变原则:

  • 原数组结构的reducer直接返回数组是符合预期的,但调整为对象结构后,UPDATE_NOTE和CREATE_NOTE两个case的返回值直接是map/concat生成的数组,而非完整的state对象。
  • 第一次触发这两个action后,原本notes对应的对象结构会被直接覆盖为数组,后续再通过state.notes.all取值时自然返回undefined,调用filter方法就会抛出你遇到的类型错误。
修复方案

修改reducer中两个case的返回逻辑,保持state的完整对象结构,只更新all字段即可:

export const reducer = (state: any = INITIAL_STATE, action: any) => {
  switch (action.type) {
    case UPDATE_NOTE: {
      return {
        ...state,
        all: state.all.map((note) =>
          note.id === action.payload.id
            ? {
                ...note,
                status: "ARCHIVED",
              }
            : note
        )
      };
    }

    case CREATE_NOTE: {
      return {
        ...state,
        all: state.all.concat([
          {
            description: 'jj',
            id: 12,
            status: NOTE_STATUS.ACTIVE,
            timestamp: CURRENT_DATE,
            images: [],
            username: "John Smith",
          },
        ])
      };
    }

    default:
      return state;
  }
};

修改后notes对应的state永远是包含all、description、images三个字段的对象,state.notes.all始终为数组,selector调用filter方法就不会报错了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:18:03