无法运行redux todo示例(todos数组未定义)

时间:2017-10-10 17:03:03

标签: javascript reactjs redux

虽然有一个非常相似的问题: Failed prop type: The prop todos[0].id is marked as required in TodoList, but its value is undefined

看起来只有症状相同(我按照建议更正了所有进口)

我可以添加一个todo元素,但是当我点击一个元素时,todos数组会变成undefined,并且以下错误会打印到控制台:

Warning: Failed prop type: The prop `todos[0]` is marked as required in `TodoList`, but its value is `undefined`.

我创建了一个最小的示例存储库,它在以下位置显示了问题: https://github.com/klaszlo/redux-todo-nonworking

((原始示例:https://github.com/reactjs/redux/tree/master/examples/todos))

重现步骤:

予。安装依赖项:

git clone https://github.com/klaszlo/redux-todo-nonworking.git
cd redux-todo-nonworking 
npm install

II。建立:

npm run build

III。运行本地服务器:

cd dist && npm run test:server

IV。在浏览器中导航到:

http://localhost:8080

诉BUG重现

  1. 添加待办事项元素
  2. 点击它(并观看javascript输出)

2 个答案:

答案 0 :(得分:0)

我经历了你的git回购。我发现你还没有在todos.js reducer中返回创建的todo对象,以便进行操作TOGGLE_TODO

case 'TOGGLE_TODO':
console.log('todo state:', state);
  return state.map(todo => {
    console.log('inside state', todo);
    return (todo.id === action.id) ? Object.assign({}, todo, {completed: !todo.completed}) : todo
  })

让我知道这是否有效。

答案 1 :(得分:0)

问题出在todos reducer TOGGLE_TODO。为了执行console.log,您已将箭头功能中的()更改为{},但忘记使用return功能所需的Array.prototype.map
使用此:

case 'TOGGLE_TODO':
console.log('todo state:', state);
  return state.map(todo => (
    (todo.id === action.id) ? Object.assign({}, todo, {completed: !todo.completed}) : todo
  )