我正在关注Redux教程并制作一个简单的TODO应用程序。该应用程序已经有几页和缩减器。这注意到我无法得到所有的待办事项(我称之为目标)因为它们没有被定义。有人有想法吗?
import React from 'react';
import { connect } from 'react-redux';
import { toggleGoal } from 'containers/CounterPage/actions'
import GoalList from 'components/GoalList'
const getVisibleGoals = (goals, filter) => {
console.log(goals)
switch (filter) {
case 'SHOW_ALL':
return goals
case 'SHOW_COMPLETED':
return goals.filter(g => g.completed)
case 'SHOW_ACTIVE':
return goals.filter(g => !g.completed)
default:
return goals
}
}
const mapStateToProps = (state) => {
return {
goals: getVisibleGoals(state.goals, state.visibilityFilter)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onGoalClick: (id) => {
dispatch(toggleGoal(id))
}
}
}
const VisibleGoal = connect(mapStateToProps,mapDispatchToProps)(GoalList);
export default VisibleGoal
减速器
/*
*
* CounterPage reducer
*
*/
import { combineReducers } from 'redux';
const goal = (state = {} , action) => {
switch (action.type) {
case 'ADD_GOAL':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_GOAL':
if (state.id !== action.id) {
return state
}
return Object.assign({}, state, {
completed: !state.completed
})
default:
return state
}
}
const goals = (state = [] , action) => {
switch (action.type) {
case 'ADD_GOAL':
return [
...state,
goal(undefined, action)
]
case 'TOGGLE_GOAL':
return state.map(t =>
goal(t, action)
)
default:
return state
}
}
const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
const counterPageReducer = combineReducers({
goals,
visibilityFilter
})
export default counterPageReducer;
OUTPUT CONSOLE
Uncaught (in promise) TypeError: Cannot read property 'goals' of undefined
at mapStateToProps (eval at ./app/containers/VisibleGoal/index.js
查看控制台日志。国家工作,但没有让目标离开州。该错误表示它无法映射未定义的
答案 0 :(得分:0)
答案是改变从州获取目标的方式
const mapStateToProps = (state) => {
return {
goals: getVisibleGoals(state.get('counterPage').goals, state.get('counterPage').visibilityFilter)
}
}
State.get('counterPage')。goals - >因为CombinedReducer