Learning Redux
上QQ阅读APP看书,第一时间看更新

Writing the posts reducer

We start with implementing the postsReducer function. First, we have to think about the function definition. This includes the initial/default state. In this case, we want to handle an array of posts, so the initial state is an empty array []. The second argument is the action. The full function definition looks as follows:

function postsReducer (state = [], action) {

We set the initial state through a default value. If the state is undefined (which it is, when the Redux store gets initialized), the state will be set to the default value (in this case, []). We will put our reducers into a separate file:

Create a new reducers.js file and import the action types we defined earlier:

import { CREATE_POST, EDIT_POST, SET_FILTER } from './actionTypes'

Then, define and export the reducer function:

export function postsReducer (state = [], action) {

In the next chapter, we will learn how to split this reducers.js file into multiple files and make a reducers/ folder.