UNPKG

template-ivan

Version:
47 lines (46 loc) 1.11 kB
import type { Reducer as ReduxReducer } from 'redux' import type { Actions } from '../actions/index' /** * reducer切片函数, 消除switch case样板代码 * * @flow * @template S * @template A * @template Actions * @param {S} initialState 初始状态 * @param {{ [key: string]: ReduxReducer<S, A> }} handlers $ObjMap<T, F> * @returns {ReduxReducer<S, A>} * @example * * const initialState = { * data, * } * function getData(state, action) { * return { * ...state, * data: action.response.data, * } * } * * function postData(state, action) { * return { * ...state, * data: action.response.data, * } * } * * export default createReducer(initialState, { * GETDATA: getData, * POSTDATA: postData, * }) */ function createReducer<S, A: Actions>( initialState: S, handlers: { [key: string]: ReduxReducer<S, A> }, ): ReduxReducer<S, A> { return (state: S = initialState, action: A): S => (Object.prototype.hasOwnProperty.call(handlers, action.type) ? handlers[action.type](state, action) : state) } export default createReducer