Redux Reducers - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
What?
- Handle state change
- It's a function takes state and action and returns new state
- 1 Store. Multiple Reducers
- All Reducers are called on each dispatch
Each reducer manipulates a slice of State.
Forbidden in Reducers
- Mutate arguments
- Perform side effects
- Call non-pure function (ex:
Date.now()
orMath.random()
)
Example
function myReducer(state, action) {
switch (action.type) {
case 'INCREMENT_COUNTER':
return(Object.assign(
{},
state,
{counter: state.counter + 1}
))
}
}
Composition Reducers
- The
courseReducer
need to "update" state'scourses
only but the reducer have to return the wholestate
object that also containsauthors
export default function courseReducer(state, action){
switch (action.type) {
case types.CREATE_COURSE_SUCCESS:
return Object.assign({}, state, {
courses: [
...state.courses,
action.course
],
authors: state.authors
});
// ...
}
}
- The reducers managing parts of the state, and combines them into a single object
export default function courseReducer(state = initialState.courses, action){
switch (action.type) {
case types.CREATE_COURSE_SUCCESS:
return [
...state.courses,
Object.assign({}, action.course)
];
// ...
}
}
- Combine reducers to one reducer
import {combineReducers} from 'redux';
import courseReducer from './courseReducer';
import authorReducer from './authorReducer';
const rootReducer = combineReducers({
courses: courseReducer
authors: authorReducer,
ajaxCallsInProgress
});
- Configure the Store
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
//...
);
}