使用 ES6 传播的基本示例

// Import the action types to recognize them
import { ACTION_ERROR, ACTION_ENTITIES_LOADED, ACTION_ENTITY_CREATED } from './actions';

// Set up a default state
const initialState = {
    error: undefined,
    entities: [],
    loading: true
};

// If no state is provided, we take the default state
export default (state = initialState, action) => {

    // Based on the type of action received, we calculate the new state
    switch(action.type) {

        // Set the error
        case ACTION_ERROR:
            // We will create new object with state,
            // which should be produced by error action
            return { 
                entities: [],
                loading: false,
                error: action.error
            };

        // Unset any error, and load the entities
        case ACTION_ENTITIES_LOADED:
            return {
                entities: action.entities,
                error: undefined,
                loading: false
            };
        
        // Add only one entity. We will use spread operator (...) to merge
        // objects properties and to create new entity
        case ACTION_ENTITY_CREATED:
            return {
                ...state,
                entities: [action.entity].concat(state.entities)
            };

        // Every action is processed by each reducer,
        // so we need to return same state if we do not want to mutate it
        default:
            return state;
    }
};