实现一个最简单的redux

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

运行结果:

实现一个最简单的redux_第1张图片
运行结果

最后是一个广告贴,最近新开了一个分享技术的公众号,欢迎大家关注

实现一个最简单的redux_第2张图片

你可能感兴趣的:(实现一个最简单的redux)