React-Redux:组合减速器失败

React-Redux: Combining reducers fails

我有一个使用 Redux 和 Redux-Thunk 构建的 React 应用程序。一切正常,直到我尝试根据 Redux docs.

组合减速器

给定一个初始的功能性减速器

export default function bigReducer(state = { events: [], flash: [] }, action) {
  switch (action.type) {
  case EVENTS_UPDATED:
    return _.extend({}, state, { events: action.pathway_events })
  case FLASH_MESSAGE_UPDATED:
    return _.extend({}, state, { flash: action.flash })
  default:
    return state
  }
}

当我尝试创建复合减速器时

function flashReducer(state = { flash: [] }, action) {
  switch (action.type) {
  case FLASH_MESSAGE_UPDATED:
    return _.extend({}, state, { flash: action.flash })
  default:
    return state
  }
}

function eventReducer(state = { events: [] }, action) {
  switch (action.type) {
  case EVENTS_UPDATED:
    return _.extend({}, state, { events: action.pathway_events })
  default:
    return state
  }
}

// either with simple reducer composition
export default function bigReducer(state = {}, action) {
  return {
    flashReducer: flashReducer(state.flash, action),
    eventReducer: eventReducer(state.events, action)
  } 
}

// or with the combineReducers function
export default const reducer = combineReducers({
  flashReducer,
  eventReducer
})

初始状态和减速器似乎混淆了

// logging the state
var EventListContainer = connect((state) => {
  console.log(state)
  return { events: state.events })(React.createClass({ ...

// returns the incorrect state
# => Object {flashReducer: Array[0], eventReducer: Array[17]}

如何使用 React 和 Redux 组合 reducer?

我从文档中的理解是,一个命名的 reducer 被委托只处理具有与 reducer 名称对应的顶级键的那部分状态。所以

const reducer = combineReducers({
  flashReducer,
  eventReducer
})

暗示你有这样的状态

const state = {
  flashReducer: {...},
  eventReducer: {...}
}

所以你需要 a) 将你的 reducer 命名为与它们应该管理的顶级键相同的名称,并且 b) 让它们的默认状态只代表完整状态对象的那个子集:

function flash(state = [], action) {
  switch (action.type) {
  case FLASH_MESSAGE_UPDATED:
    return action.flash.slice()
  default:
    return state
  }
}

function events(state = [], action) {
  switch (action.type) {
  case EVENTS_UPDATED:
    return action.pathway_events.slice()
  default:
    return state
  }
}

const reducer = combineReducers({
  flash,
  events
})