原文地址:https://github.com/huruji/blog/issues/1

redux的主要API集中在createStore函数返回值中,以下这个迷你的redux只简单实现createStore、dispatch、subscribe、getState方法,如下:

const createStore = function(reducer, initialState){
  let currentState = undefined;
  if(initialState) {
    currentState = initialState;
  }
  let currentReducer = reducer;
  let listeners = [];
  return {
    getState() {
      return currentState;
    },
    dispatch(action) {
      if(!currentState){
        currentState = currentReducer(currentState, action);
      }
      currentState = currentReducer(currentState, action);
      listeners.forEach((item) => {
        item();
      });
      return this;
    },
    subscribe(fn) {
      listeners.push(fn);
    }
  }
};

测试代码:

let reducer = function(state, action) {
  if(!state) {
    return {counter: 0};
  }
  switch(action.type) {
    case 'ADD':
      return {counter: state.counter+1};
    case 'DEL':
      return {counter: state.counter-1};
    default:
      return state;
  }
};
let store = createStore(reducer);

store.subscribe(function(){
  console.log('before1')
});
store.subscribe(function() {
  console.log('before2')
});

store.dispatch({
  type:'ADD'
});
console.log(store.getState());
store.dispatch({
  type: 'ADD'
});
console.log(store.getState());
store.dispatch({
  type: 'DEL'
});
console.log(store.getState());

运行结果:

运行结果


灰风GreyWind
308 声望13 粉丝

灰风也叫忽如寄