我正在关注关于 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/