huruji / blog

红日初升,其道大光:sun_with_face::house_with_garden:请star或watch,不要fork
https://juejin.im/user/5894886f2f301e00693a3e49/posts
158 stars 11 forks source link

动手实现一个最简单的redux #1

Open huruji opened 7 years ago

huruji commented 7 years ago

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

运行结果:

运行结果