Redux fundamentals

June 15, 2017

function createStore(reducer) {
  let state, listener = [], getState, dispatch, subscribe;
  dispatch = action => {
    state = reducer(state, action)
    listener.forEach(item => item())
  }
  dispatch({})
  subscribe = fn => {
    listener = [...listener, fn]
    return () => {
      listener = listener.filter(item => item !== fn)
    }
  }
  getState = () => JSON.parse(JSON.stringify(state))
  return {dispatch, getState, subscribe}
}
/**
 * combineReducers 合并reducers
 * @param reducers[Object] 接收一个对象
 * @returns {function()}
 */
function combineReducers(reducers) {

  return (state = {}, action) => {
    let obj = {}
    for (let key in reducers) {
      if(!reducers.hasOwnProperty(key)) continue;
      obj[key] = reducers[key](state[key], action)
    }
    return obj
  }
}

/**
 * bindActionCreators 合并actions返回使用dispatch包装的结果
 * @param actions
 * @param dispatch
 * @returns {{}}
 */
function bindActionCreators(actions,dispatch) {
  //将actions 包装成 mapDispatchToProps返回的对象

  let obj={};
  for(let key in actions){
    if(!actions.hasOwnProperty(key)) continue;
    obj[key]=(...arg)=>{
      dispatch(actions[key](...arg))
    }
  }
  return obj;

}

Profile picture

Written by leon build everything from scratch You should follow them on Github