动手实现一个最简单的redux

2019-07-24 14:24:30 浏览数 (1)

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

代码语言:javascript复制
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);
    }
  }
};

测试代码:

代码语言:javascript复制
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());

运行结果:

0 人点赞