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

开发Redux待办列表时combineReducers配合TypeScript报错如何解决

错误原因

你的TodoReducer没有返回符合约定的状态值,Redux的reducer要求无论触发什么action,都必须返回对应模块的状态对象,当前你的TodoReducer仅执行了打印逻辑,无任何返回值,默认返回undefined,和combineReducers要求的TodoState类型不匹配,因此抛出类型错误。

修复方法

修改TodoReducer.ts文件,补全reducer的分支处理逻辑与返回值:

import { TodoState, TodoAction } from "global";

const INITIAL_STATE: TodoState = {
  todoList: [],
};

// 显式标注函数返回值为TodoState,提前做类型校验
export const TodoReducer = (state = INITIAL_STATE, action: TodoAction): TodoState => {
  console.log(state, action);
  switch(action.type) {
    case "ADD_TODO":
      // 新增待办时返回新的state
      return {
        ...state,
        todoList: [...state.todoList, action.payload]
      };
    case "REMOVE_TODO":
      // 删除待办时返回过滤后的新state
      return {
        ...state,
        todoList: state.todoList.filter(item => item.id !== action.payload.id)
      };
    default:
      // 未匹配到对应action时返回当前state,不可省略
      return state;
  }
};

额外优化建议:你在全局类型定义和store/index.ts中重复定义了AppState接口,建议删掉store/index.ts里的重复定义,直接导入全局的AppState使用,避免后续出现类型不一致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:45:03