基本減速機
基本的減速器看起來像這樣:
// Import the action types to recognise them
import { ACTION_ERROR, ACTION_ENTITIES_LOADED, ACTION_ENTITY_CREATED } from './actions';
// Set up a default state
const initialState = {
error: undefined,
entities: []
};
// If no state is provided, we take the default state
export default (state = initilState, action) => {
// Based on the type of action received, we calculate the new state
switch(action.type) {
// Set the error
case ACTION_ERROR:
// Note that we create a new object, copy the current state into it,
// and then we make the relevant changes, so we don't mutate the state
return Object.assign({}, state, { error: action.error });
// Unset any error, and load the entitites
case ACTION_ENTITIES_LOADED:
return Object.assign({}, state, {
entities: action.entities,
error: undefined
};
// Add only one entity. Again, note how we make a new entities array
// combining the previous one with the new entity
// instead of directly modifying it, so we don't mutate the state.
case ACTION_ENTITY_CREATED:
return Object.assign({}, state, {
entities: [action.entity].concat(state.entities)
}):
// If the action is not relevant to this reducer, just return the state
// as it was before.
default:
return state;
}
};