我正在关注Redux上的egghead.io教程。我在第17课,并得到丹阿布拉莫夫不是的错误。代码如下。
我得到的错误是
"TypeError: Cannot read property 'map' of undefined
根据我的理解,我收到错误,因为当我渲染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()
答案 0 :(得分:2)
您合并了减速机,但是您只使用todos
减速机而不是合并减速机来创建商店。
const todoApp = combineReducers({
todos,
visbilityFilter
});
const { createStore } = Redux;
const store = createStore(todos); // <--- should be `todoApp`