无法读取未定义的'map'属性

时间:2017-06-24 20:41:29

标签: javascript redux

我浏览了Redux教程并练习了自己实现的一些示例(以确保我理解它们是如何工作的)。

我收到错误Cannot read property 'map' of undefined

代码:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
import { createStore } from 'redux'




const todo = (state, action) => {
    console.log('todo ran')
    switch (action.type) {
        case 'ADD_TODO':
            return {
                id: action.id,
                text: action.text
            }
        default:
            return state
    }
}

const todos = (state = [], action) => {
    console.log('todos ran')
    switch (action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                todo(undefined, action)
            ];
    }
}
//Just updated this to include an empty list
let store = createStore(todos, [])


let nextTodoId = 0
const AddTodo = () => {
    let input;

    return (
        <div>
            <input ref={node => {input = node}}/>
            <button onClick = {() => {
                store.dispatch({
                    type: 'ADD_TODO',
                    id: nextTodoId++,
                    text: input.value
                });
                input.value = ''
            }}>
                Add Todo
            </button>
            <ul>
                {store.getState().map(item => 
                    <li key={item.id}> {item.text} </li>
                )}
            </ul>
            <button onClick = {() => console.log(store.getState())}>Print State</button>

        </div>
    )
};


ReactDOM.render(
    <AddTodo />,
    document.getElementById('root'));

我以为我正在传递一个空状态[]并且我会将其映射到那个状态。但似乎state未定义。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您错过了将初始状态传递给createStore来电。

尝试以下方法:

let store = createStore(todos, [])

答案 1 :(得分:0)

我忘了添加:

default: return state

位于todos的底部。