In the Redux basics tutorial section on Reducers I can't quite understand how the following syntax deduces which subset of the app state to pass to each reducer referenced in the call to combineReducers. Is it purely matching the state member name on the reducer name?
import { combineReducers } from 'redux'
import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './actions'
const { SHOW_ALL } = VisibilityFilters
function visibilityFilter(state = SHOW_ALL, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return action.filter
default:
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false
}
]
case COMPLETE_TODO:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}
const todoApp = combineReducers({
visibilityFilter,
todos
})
export default todoApp
If the application's state is managed by Redux, the changes happen inside a reducer function — this is the only place where state changes happen. The reducer function makes use of the initial state of the application and something called action, to determine what the new state will look like.
The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore .
There are two main ways to initialize state for your application. The createStore method can accept an optional preloadedState value as its second argument. Reducers can also specify an initial value by looking for an incoming state argument that is undefined , and returning the value they'd like to use as a default.
If the new state is different, the reducer must create new object, and making a copy is a way to describe the unchanged part.
Regarding your specific question about how this works with the combineReducers
function, just check out the source code. You can see in combineReducers.js in the redux repo that as the action goes through every reducer that's been combined, each individual reducer gets passed the branch of state that matches its corresponding key in the object you pass to combineReducers
.
So in your example, both the visibilityFilter
and todos
reducers have keys of the same name (because of the ES6 object property shorthand you're using). And those keys are what are used to pass the specific branches of state to each respective reducer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With