動手實現一個最簡單的redux

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

redux的主要API集中在createStore函數返回值中,如下這個迷你的redux只簡單實現createStore、dispatch、subscribe、getState方法,以下:github

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);
    }
  }
};

測試代碼:redux

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());

運行結果:函數

運行結果

相關文章
相關標籤/搜索