redux源码解析

核心功能

  • getState 获取当前的state
  • dispatch 派发action以更新状态
  • subscribe 订阅与退订
  • 生成actionCreator
  • 合并reducer
    1 getState
function getState(){
   return currentState;
}

2 dispatch

function dispatch(action){
  currentState = currentReducer(state, action)
  listeners.forEach(fn => fn())
}

3 订阅

let listeners = []
function subscribe(listener){
  listeners.push(listener)
  return function(){
    listeners.filter(fn => fn !== listener)
  }
}

4 合并reducers

function combineReducers(reducers){
  let combineState;
  Object.keys(reducers).forEach(name => {
    combineState[name] = reducers[name](state, action)
  })
  return combineState
}
function createStore(reducer) {

  let currentState;
  let currentReducer = reducer;
  let listeners = [];
  
  function getState() {
    return currentState;
  }

  function dispatch(action) {
    currentState = currentReducer(currentState, action);
    listeners.forEach(l => l())
  }

  function subscribe(listener) {
    listeners.push(listener);
    return function () {
      listeners.filter(fn => fn!= listener)
    }
  }
  
  function combineReducer(reducers){
    return function(state = {}, action){
      let combineState = {}
      Object.keys(reducers).forEach(name => {
        combineState[name]  = reducers[name](state, action)
      })
      return combineState;
    }
  }

  dispatch({
    type: '@@redux/INIT'
  })

  return {
    getState,
    dispatch,
    subscribe
  }
  
}

export { createStore }

中间件原理

主要是改装dispatch

你可能感兴趣的:(redux源码解析)