React-Redux:组合Reducer失败

时间:2015-11-10 18:22:27

标签: reactjs redux

我有一个使用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?

1 个答案:

答案 0 :(得分:8)

我对文档的理解是,委托命名的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
})