redux源码全解析

redux源码的核心在src文件夹里,这篇文章主要针对于src里的js文件做一下解析。其实源码中的注释已经足够详细了,写这篇文章一方面为了巩固自己的知识,另一方面也能让大家指出来有什么不足之处。


  • createStore

首先来看最基本的createStore函数,在此我省略掉了一些类型判断和抛错,留下了核心内容。
createStore最终返回的对象里包含有以下函数(注:本文对observable函数不做详解,主要是笔者没发现这玩意有什么用^_^):
1.dispatch 发送一个action改变state
2.subscribe 订阅观察state变化
3.getState 获取当前的state
4.replaceReducer 替换当前的reducer函数
代码中有详细介绍

function createStore(reducer, preloadedState, enhancer) {
  //@param {Function} reducer 处理各个action的函数,返回新的state
  //@param {any} preloadedState 初始的state
  //@param {Function} enhancer 中间件函数,用来强化dispatch的作用
  
  //下面两个判断主要是为了处理enhancer
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState
    preloadedState = undefined
  }
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }
    return enhancer(createStore)(reducer, preloadedState)
  }
  let currentReducer = reducer  //当前reducer
  let currentState = preloadedState  //当前state
  let currentListeners = []      //当前的listeners
  let nextListeners = currentListeners  //接下来的listeners
  let isDispatching = false      //是否在dispatch

  function ensureCanMutateNextListeners() {
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice()
    }
  }
  
  /**
  * 获取当前的state
  */
  function getState() {
    return currentState
  }

  /**
   * 订阅注册,一旦dispatch被执行,所有观察者都能收到信息
   * 以react为例,怎么才能做到每次state树变化都能自动更新呢?我们会用到 
   * subscribe(render), 这样每次dispatch都能调用一次render函数。但是每个页面都要注册一 
   * 下太麻烦了,在react-redux里我们会有更简便的方法。关于react-redux源码解析我会在下一 
   * 篇文章中写
   * @param {Function} listener 观察者
   */
  function subscribe(listener) {
    if (typeof listener !== 'function') {
      throw new Error('Expected listener to be a function.')
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)  //添加listener
    
    //此处返回了一个取消订阅的函数
    return function unsubscribe() {
      if (!isSubscribed) {  //如果没有订阅,直接返回
        return
      }

      isSubscribed = false  //取消订阅了,所以设置为false

      ensureCanMutateNextListeners()
      
      //获取该listener在数组中的index
      const index = nextListeners.indexOf(listener)
      
      //从数组中删除该listener
      nextListeners.splice(index, 1)
    }
  }
  
  /**
  *  发起一个action来改变state
  *  @param {Object} action
  */
  function dispatch(action) {
    //如果有dispatch正在进行,会报错
    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }
    
    //调用reducer更新state,并且更新isDispatching
    try {
      isDispatching = true
      currentState = currentReducer(currentState, action)
    } finally {
      isDispatching = false
    }
    
    //通知所有的观察者,调用其函数
    const listeners = currentListeners = nextListeners
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      listener()
    }
    
    //返回了action,但是本人觉得可有可无,通常用不到
    return action
  }

  /**
   * 替换当前的reducer,这个通常是在需要动态加载reducers时候才用得到
   * @param {Function} nextReducer
   */
  function replaceReducer(nextReducer) {
    currentReducer = nextReducer
    dispatch({ type: ActionTypes.INIT })
  }

  // 当一个store被创建时,会立即dispatch一个初始的action。官方的说法是这样做可以        
  // 'effectively populate' 初始的state树
  dispatch({ type: ActionTypes.INIT })

  return {
    dispatch,
    subscribe,
    getState,
    replaceReducer,
    [$$observable]: observable
  }
}



  • compose

compose是一个工具函数,只有短短几行,精华就包含在最后一行内(真是体现了函数式编程的精髓)

function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }
  if (funcs.length === 1) {
    return funcs[0]
  }
  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

compose的作用是将一个函数类型的数组组合起来,使他们能够进行链式调用。
用法举例:
compose([a,b,c])(params) 可以转化为 a(b(c(params)))
这个函数主要用于applyMiddleware中。


  • applyMiddleware

这个函数通常出现的形式如下(省略preloadedState)
let store = createStore(reducer, applyMiddleware([middlewares]))
不难看出,这个函数是用来组合中间件的。
回顾之前的createStore函数,我们可以发现createStore(reducer, applyMiddleware([middlewares]))
会得到 applyMiddleware([middlewares])(createStore)(reducer, undefined)
在此之前我们得先了解一下中间件是干嘛的。
直白一点:中间件就是用来强化dispatch函数的
我们知道dispatch函数是用来更新state的,但是要是我们想要做一些额外的动作的?比如在更新state前后打印一下当前的state,或者我们想要用redux处理异步请求,都需要用到中间件。

function applyMiddleware(...middlewares) {
  //返回一个函数,
  return (createStore) => (reducer, preloadedState, enhancer) => {
    //创建store
    const store = createStore(reducer, preloadedState, enhancer)
    //获取store的dispatch函数
    let dispatch = store.dispatch
    //存储中间件
    let chain = []
    
    //这个对象包含的是store的两个函数getState和disptach
    const middlewareAPI = {
      getState: store.getState,
      dispatch: (action) => dispatch(action)
    }
    
    //对于中间件数组的每一个元素,调用其方法传入getState和dispatch函数,获得一个函数类型 
    //的数组。从这里我们可以看出每一个中间件的类型都是一个函数。关于中间件看下一个例子。
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    //组合中间件函数,强化disptach函数
    //此时chain中每个元素是的类型是 dispatch=>action={},第一次传入一个store.dispatch
    //得到的其实是一个强化过一次的disptach函数,然后作为参数再传入下一个中间件,直到最后 
    //一个中间件,最终得到历经所有中间件强化过后的disptach函数
    dispatch = compose(...chain)(store.dispatch)
    
    //返回store(包含强化后的dispatch函数)
    return {
      ...store,
      dispatch
    }
  }
}

关于中间件,我们以在dispatch前后打印state信息为例。最直观的的我们想到

function logger(store) {
  return (action)=>{
  console.log(store.getState())
  store.dispatch(action)
  console.log(store.getState())
  }
}

其实这样写我们需要的功能已经能达到,但是不能达到链式调用的功能。因此我们需要把dispatch提出来。

function logger(store) {
  return dispatch=>action=>{
  console.log(store.getState())
  dispatch(action)
  console.log(store.getState())
  }
}

再回过头去看applyMiddleware里关于chain的操作就很清楚了


  • combineReducers

这个函数的作用是返回一个新的reducer函数能够触发之前传入的所有的reducer来更新state。用于reducer的拆分。
比如有一个Object是let a={reducer1:fun1,reducer2:fun2}
combineReducers(a)就能获得一个新的reducer处理所有action

/**
* @param {Object} reducers 每个key对应一个reducer
*/
function combineReducers(reducers) {
  //获取所有key
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  
  //深拷贝reducers
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]

    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key]
    }
  }
  const finalReducerKeys = Object.keys(finalReducers)
  
  //新的reducer函数
  //@param {Object} state {state1:..., state2:..., ...}每个state对应一个reducer
  //@param {Object} action
  return function combination(state = {}, action) {
    let hasChanged = false
    //更新后的state
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      //上一次state
      const previousStateForKey = state[key]
      
      //用当前的reducer更新state,每个reducer会对应一个state
      const nextStateForKey = reducer(previousStateForKey, action)
      
      //更新总的state
      nextState[key] = nextStateForKey
      
      //判断是否发生变化
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}



  • bindActionCreators

暂时没发现这个函数有什么具体的作用

//actionCreator是一个返回action的函数
//返回一个函数,这个函数会直接dispatch一个由actionCreator创建的action
function bindActionCreator(actionCreator, dispatch) {
  return (...args) => dispatch(actionCreator(...args))
}
/**
* @param {Function|Object} actionCreators 返回action的函数或者key是 返回action        
*                           的函数
* @param {Function} dispatch 跟createStore里的dispatch函数一样
* @return 返回一个函数列表,这些函数会直接dispatch一个由actionCreator创建的action
*/
function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch)
  }   
  const keys = Object.keys(actionCreators)
  const boundActionCreators = {}
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  return boundActionCreators
}

评论

暂无评论