【问题标题】:React-Redux: Combining reducers failsReact-Redux:组合减速器失败
【发布时间】:2016-02-11 17:43:23
【问题描述】:

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

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

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

    【讨论】:

    • 查看我的更新。您不需要根据状态键命名减速器功能,但如果您使用combineReducers,则需要将减速器键与状态键对齐。
    • 抱歉有任何混淆,有一个习惯是先发布最低答案,然后将扩展答案作为更新。
    • 尤里卡,做到了。不知道我是怎么错过的,这很关键。谢谢。
    • 这非常有用。 Redux 文档中根本没有提到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2018-09-18
    • 2020-07-07
    • 2017-10-18
    • 2016-11-23
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多