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

React Redux中TypeError读取todos未定义问题修复求助

修复Todo功能的TypeError问题

问题原因

报错TypeError: Cannot read properties of undefined (reading 'todos')的核心原因:

  • Store配置中直接将todoSlice对象赋值给todo reducer,而非todoSlice提供的真正reducer函数
  • 导致Redux state中不存在state.todo有效节点,无法读取state.todo.todos

修复步骤

1. 修正Store配置

找到你的store配置文件,将todo: todoSlice改为todo: todoSlice.reducer:

// 修改后的store配置
reducer: {
    todo: todoSlice.reducer, // 必须使用slice的reducer属性
    user: userReducer,
  },
});

2. 完善TodoSlice的导出(必要操作)

在todoSlice.js中添加reducer和action的导出,确保store能正确引用:

const initialState = {
  todos: [],
};
export const todoSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    addTodo: (state, action) => {
      state.todos.push(action.payload);
    },
    removeTodo: (state, action) => {
      state.todos = state.todos.filter((todo) => todo.id !== action.payload);
    },
    completedTodo: (state, action) => {
      const toggleTodo = state.todos.find((todo) => todo.id === action.payload);
      toggleTodo.completed = !toggleTodo.completed;
    },
  },
});

// 导出action creators供组件调用
export const { addTodo, removeTodo, completedTodo } = todoSlice.actions;
// 导出reducer供store使用
export default todoSlice.reducer;

3. 确认TodoForm中的Selector逻辑

TodoForm.js中的useSelector写法正确,无需修改:

const todos = useSelector((state) => state.todo.todos);

验证修复

重新运行项目后,state.todo会正确映射到todo slice的状态,todos数组可正常读取和操作,Todo功能即可恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:15:31