
上QQ阅读APP看书,第一时间看更新
Writing the filter reducer
Similar to the postsReducer, we could define a filterReducer function that takes care of handling the filter part of our state object. By default, we want to show all posts, so we set the default state to 'all'.
The filterReducer only handles one action type, so an if/else statement can be used. If the reducer function grows and ends up handling more action types, it is a good idea to use a switch statement instead.
Define the reducer function in the src/reducers.js file:
function filterReducer (state = 'all', action) {
if (action.type === SET_FILTER) {
return action.filter
} else {
return state
}
}
This reducer function is pretty simple—it sets the filter state to whatever is entered in action.filter.
Note that we still need to take care of making use of the filter state when rendering our application, the reducer only takes care of state changes, not how they are applied to the user interface.