javascript - Egghead.io Redux 教程 - 第 17 课 : "TypeError: Cannot read property ' map' of undefined

标签 javascript reactjs

我正在关注关于 Redux 的 egghead.io 教程。我在第 17 课上遇到了 Dan Abramov 没有的错误。代码如下。

我得到的错误是

“类型错误:无法读取未定义的属性‘map’

根据我的理解,我收到错误是因为当我呈现 TodoApp 时,它试图映射到空的 this.props.todos 上。但是他没有收到任何错误?

我做错了什么?

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id:action.id,
        text: action.text,
        completed: false
      }

    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state;
      }

      return {
        ...state,
        completed: !state.completed
      };

    default:
      return state
  }
}

const todos = (state = [], action) => {
  switch(action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ];

    case 'TOGGLE_TODO':
      return state.map(t => todo(t, action))  

    default:
      return state;
  }
};

const visbilityFilter = (
  state = 'SHOW_ALL',
  action
) => {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
}

const { combineReducers } = Redux
const todoApp = combineReducers({
  todos,
  visbilityFilter
});

const { createStore } = Redux;
const store = createStore(todos);

const { Component } = React;

let nextTodoId = 0

class TodoApp extends Component {
  render() {
    return (
      <div>
        <button onClick = {() => {
          store.dispatch({
            type: 'ADD_TODO', 
            text: 'Test', 
            id: nextTodoId++
          })
        }}>
          Add Todo
        </button>
        <ul>
          {this.props.todos.map(todo =>
            <li key={todo.id}>
              {todo.text}
            </li>
          )}
        </ul>
      </div>

    )
  }
}

const render = () => {
  ReactDOM.render(
    <TodoApp todos={store.getState().todos} />,
    document.getElementById('root')
  )
};

store.subscribe(render);

render()

最佳答案

您组合了您的 reducer,但您只使用 todos reducer 而不是组合的 reducer 创建了您的商店。

const todoApp = combineReducers({
  todos,
  visbilityFilter
});

const { createStore } = Redux;
const store = createStore(todos); // <--- should be `todoApp`

关于javascript - Egghead.io Redux 教程 - 第 17 课 : "TypeError: Cannot read property ' map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593155/

相关文章:

javascript - Angularjs (ionic) 列表滑动按钮

javascript - 移动网络点击背景颜色?

javascript - 如何在javascript中获取隐藏列表的值

javascript - 在 React 中切换 aria-pressed 角色以实现 Web 可访问性的最有效方法

javascript - 当卸载/重用 React 组件时,如何取消 Promise 中的下一个 'then'?

javascript - 使用 D3 DataMaps 选择 SVG 项目?

reactjs - React-native 调试 apk

javascript - 显示 RSS 源中的图像

javascript - 如何在 Reactjs 中使用 Select2?

javascript - 闭包在类方法上的工作方式是否相同?