React-Redux: Combining Gearboxes Fails

I have a React application built using Redux and Redux-Thunk. Everything works fine until I try to combine reducers in Redux docs .

For the original, functional gearbox

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 } } 

When I try to create a compound gearbox

 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 }) 

initial state and gears seem to mix

 // 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]} 

How can I combine gears with React and Redux?

+5
source share
1 answer

My understanding from the documents is that the named reducer is delegated to process only that part of the state with the top-level key corresponding to the name of the reducer. So

 const reducer = combineReducers({ flashReducer, eventReducer }) 

means you have a state like

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

So, you need to: a) name your gearboxes the same as the top-level keys that they need to control, and b) have a default state only for this subset of the full state object:

 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 }) 
+8
source

Source: https://habr.com/ru/post/1235632/


All Articles