开发者问题收集

在 Redux 中添加 Todo,无法读取属性 Symbol(Symbol.iterator)

2020-08-11
360

我要向数组中添加一个对象,第二次我想添加另一个对象时,整个数组变成了第一,最终出现错误,我的目标是使用 Redux 为 Todo 程序添加一个任务。

我也收到此错误:

TypeError: Cannot read property 'length' of undefined
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

//todoReducer.js

import {ADD_TODO} from '../Actions/Todo';

const initialState = {
  todos:[],
};


const handleAddTodo = (state, action) => {
  const {todos} = state;
 
  const newTodo =[...todos, {
    id: todos.length + 1,
    text: action.title,
    isComplete: false,
  }]
  return (
    todos.push(newTodo)
  )
}

export default function todoRDS(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return handleAddTodo(state, action)
    default:
      return state
  }

}
2个回答

更改返回函数,否则将返回错误值。您需要返回状态

const handleAddTodo = (state, action) => {
  const {todos} = state;
 
  return {
...state,
todos: [...todos, {
    id: todos.length + 1,
    text: action.title,
    isComplete: false,
  }]
}
}
Omar Sy
2020-08-11
export default function todoRDS(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return {...state, todos: [...state.todos, { id: state.todos.length +1, title: action.title, isComplete: false }] }
    default:
      return state
  }

}

state 在 react 和 redux 中是不可变的,您需要使用旧状态值创建一个新状态,并在该新对象中添加新的待办事项。如果您仍想使用 handeAddTodo,请尝试以下操作:

const handleAddTodo = (state, action) => { return {...state, todos: [...state.todos, { id: state.todos.length +1, title: action.title, isComplete: false }] }

Yunus Emre
2020-08-11