react-redux开发todo应用时出现Cannot read property 'map' of undefined报错
错误根因
TypeError: Cannot read property 'map' of undefined报错的核心原因是你调用map方法的list变量为undefined,不具备数组的map方法,由以下几个代码问题共同导致:
- 取值来源错误:你从
state.todoList.text取值,但TodoListReducer初始值为数组,不存在text属性,首次渲染时拿到的值就是undefined - 数据对应关系错误:你的待办列表实际存在
TodoReducer中(对应全局状态的state.todos字段),却错误从存临时输入值的TodoListReducer中取列表数据 - 渲染逻辑错误:
map回调没有返回值,且待办内容没有正确插值渲染 - 新增待办逻辑错误:
ADD_TODO操作直接覆盖原有待办数组,没有追加新内容
修复步骤
1. 修改TodoList.js的取值和渲染逻辑
import React from "react"; import { useSelector } from "react-redux"; const TodoList = () => { // 从正确的reducer取待办列表,加默认空数组避免边界情况报错 const list = useSelector((state) => state.todos) || []; return ( <div> {/* map回调用小括号隐式返回,加key属性,插值渲染todo的text字段 */} {list.map((todo, index)=> ( <li key={index}>{todo.text}</li> ))} </div> ); } export default TodoList;
2. 修改TodoReducer的ADD_TODO逻辑,实现追加待办而非覆盖
export const TodoReducer = (state = initial_state, action) => { switch (action.type) { case ADD_TODO: // 展开原有待办数组,追加新待办项 return [...state, { text: action.text, }] default: return state; } }
3. (可选)修复TodoListReducer的初始值结构
如果你的TodoListReducer是用来存输入框临时值,把它的初始值改为对象,避免后续取值异常:
// 单独定义TodoListReducer的初始值为对象结构 const todoListInitialState = { text:"" } export const TodoListReducer = (state = todoListInitialState, action) => { switch (action.type) { case SET_VALUE: return { ...state, text: action.text } default: return state; } }
内容的提问来源于stack exchange,提问作者surrealduck
相关产品推荐
相关产品推荐

