Redux(四):源码分析之createStore

2020-06-01 14:30:29 浏览数 (1)

一、createStore的作用

createStore用来创建一个store来维护state树。改变store中state的唯一方式就是调用store的dispatch()方法。一个应用应该只包含一个状态树,为了让state树的不同部分去响应action,可能需要使用combineReducers()方法将多个reducers组合成一个reducer。

1.1 基本使用

语法:

createStore(reducer,preloadedState,enhancer);

参数:

  • reducer:函数类型,必须。传入当前state树和action作为参数,并返回下一个state树。
  • preloadedState:任意类型,非必须。初始的state,可以由服务端返回,也可以是本地的会话保存。如果使用了combineReducers()函数来创建根reducer,那么这个值必须是一个对象,且和combineReducers()函数的参数对象拥有相同key。(注:结合es6的解构赋值,可以在根reducer的参数中初始化,也可以结合combineReducers在子reducer的参数中初始化。所以通常可以不用指定preloadedState)。
  • enhancer:函数类型,非必须。用于增强redux的功能,通常与之结合的就是中间件系统。

返回值:

返回一个redux store,包含一些方法如:dispatch()、subscribe()、getState()等。

二、createStore.js源码分析

目标文件:/node_modules/redux/src/createStore.js

版本:^4.0.1

该文件通过export default导出了一个函数——createStore。

1、32行——41行

不可以传递多个enhancer参数,只能将其组合成一个enhancer。

代码语言:javascript复制
  if (
    (typeof preloadedState === 'function' && typeof enhancer === 'function') ||
    (typeof enhancer === 'function' && typeof arguments[3] === 'function')
  ) {
    throw new Error(
      'It looks like you are passing several store enhancers to '  
        'createStore(). This is not supported. Instead, compose them '  
        'together to a single function'
    )
  }

preloadedState是非必须参数,所以当判断到@param2、@param3都是函数或者@param3、@param4都是函数,则抛出异常。

2、43行——46行

如果@param2是函数且@param3是undefined,则对preloadedState和enhaner参数进行重置。

代码语言:javascript复制
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState
    preloadedState = undefined
  }

3、48行——58行

如果enhancer不为空则必须是一个函数。

代码语言:javascript复制
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }

    return enhancer(createStore)(reducer, preloadedState)
  }

  if (typeof reducer !== 'function') {
    throw new Error('Expected the reducer to be a function.')
  }

可以看出enhancer类似这样的结构:

代码语言:javascript复制
function enhancer(createStore) {
  return function(reducer,preloadedState){
    /*
    * 
    * */
  }
}

里面的匿名函数应该是返回一个包含如:dispatch()、subscribe()、getState()方法的对象,但不确定,继续。

4、60行——70行

变量初始化及参数拷贝。

代码语言:javascript复制
  let currentReducer = reducer
  let currentState = preloadedState
  let currentListeners = []
  let nextListeners = currentListeners
  let isDispatching = false

  function ensureCanMutateNextListeners() {
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice()
    }
  }

js中对象、函数、数组等是按地址引用的,所以这里应该是为了避免地址应用导致的一些其它问题,所以做了一些赋值。

  • currentReducer:根reducer函数
  • currentState:初始化state(可能是undefined)
  • currentListeners:应该用来存放之后subscribe注册的监听函数
  • nextListeners:结合ensureCanMutateNextListeners()函数,应该是用来拷贝currentListeners的
  • isDispatching:避免在reducer函数中调用getState()

(slice方法会返回一个新的数组,不传参数可以快速生成一个副本。)

5、72行——87行

定义getState()函数,用于返回当前的state树。

代码语言:javascript复制
  /**
   * Reads the state tree managed by the store.
   *
   * @returns {any} The current state tree of your application.
   */
  function getState() {
    if (isDispatching) {
      throw new Error(
        'You may not call store.getState() while the reducer is executing. '  
          'The reducer has already received the state as an argument. '  
          'Pass it down from the top reducer instead of reading it from the store.'
      )
    }

    return currentState
  }

reducer执行之前应该会将isDispatching置为true,这个判断将不允许在reducer内部直接调用getState()方法来获取state,避免数据不同步或死循环。

6、89行——149行

定义subscribe()监听器函数。

代码语言:javascript复制
  /**
   * Adds a change listener. It will be called any time an action is dispatched,
   * and some part of the state tree may potentially have changed. You may then
   * call `getState()` to read the current state tree inside the callback.
   *
   * You may call `dispatch()` from a change listener, with the following
   * caveats:
   *
   * 1. The subscriptions are snapshotted just before every `dispatch()` call.
   * If you subscribe or unsubscribe while the listeners are being invoked, this
   * will not have any effect on the `dispatch()` that is currently in progress.
   * However, the next `dispatch()` call, whether nested or not, will use a more
   * recent snapshot of the subscription list.
   *
   * 2. The listener should not expect to see all state changes, as the state
   * might have been updated multiple times during a nested `dispatch()` before
   * the listener is called. It is, however, guaranteed that all subscribers
   * registered before the `dispatch()` started will be called with the latest
   * state by the time it exits.
   *
   * @param {Function} listener A callback to be invoked on every dispatch.
   * @returns {Function} A function to remove this change listener.
   */
  function subscribe(listener) {
    if (typeof listener !== 'function') {
      throw new Error('Expected the listener to be a function.')
    }

    if (isDispatching) {
      throw new Error(
        'You may not call store.subscribe() while the reducer is executing. '  
          'If you would like to be notified after the store has been updated, subscribe from a '  
          'component and invoke store.getState() in the callback to access the latest state. '  
          'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
      )
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)

    return function unsubscribe() {
      if (!isSubscribed) {
        return
      }

      if (isDispatching) {
        throw new Error(
          'You may not unsubscribe from a store listener while the reducer is executing. '  
            'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
        )
      }

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      nextListeners.splice(index, 1)
    }
  }

subscribe()会接收一个回调函数作为参数,然后将该回调函数push进nextListeners中,当action派发结束后会依次执行数组nextListeners中的回调函数。

subscribe()会返回一个函数,调用该函数可以取消之前注册的回调函数。

  • isDispatching为真,即派发结束之前不可以注册新的回调函数。
  • 同理,派发结束之前也不可以取消注册的回调函数。
  • isSubscribed变量用来确保取消注册只能生效1次。

在这个回调函数里面执行getState()方法可以获取到更新后的state树。

注释也提到:也可以在subscribe注册的回调函数中继续派发action,但不加任何判断语句直接派发action,会导致死循环,那实际这里的应用场景是什么呢?

7、151行——209行

定义dispatch()派发器函数。

代码语言:javascript复制
  /**
   * Dispatches an action. It is the only way to trigger a state change.
   *
   * The `reducer` function, used to create the store, will be called with the
   * current state tree and the given `action`. Its return value will
   * be considered the **next** state of the tree, and the change listeners
   * will be notified.
   *
   * The base implementation only supports plain object actions. If you want to
   * dispatch a Promise, an Observable, a thunk, or something else, you need to
   * wrap your store creating function into the corresponding middleware. For
   * example, see the documentation for the `redux-thunk` package. Even the
   * middleware will eventually dispatch plain object actions using this method.
   *
   * @param {Object} action A plain object representing “what changed”. It is
   * a good idea to keep actions serializable so you can record and replay user
   * sessions, or use the time travelling `redux-devtools`. An action must have
   * a `type` property which may not be `undefined`. It is a good idea to use
   * string constants for action types.
   *
   * @returns {Object} For convenience, the same action object you dispatched.
   *
   * Note that, if you use a custom middleware, it may wrap `dispatch()` to
   * return something else (for example, a Promise you can await).
   */
  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. '  
          'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. '  
          'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }

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

    return action
  }

dispatch()函数接收一个action作为参数,通常这个action是一个包含type属性的纯对象。通过中间件的拓展,action可以是promise、函数,但最终传递给底层的依然是纯对象。

195行处可以看到执行reducer来计算得出新的currentState并覆盖之前的值。新的state计算结束后,遍历currentListeners并执行存放的回调函数,最后返回action本身。

7、211行——228行

定义replaceReducer()函数,顾名思义用来替换reducer。

代码语言:javascript复制
  /**
   * Replaces the reducer currently used by the store to calculate the state.
   *
   * You might need this if your app implements code splitting and you want to
   * load some of the reducers dynamically. You might also need this if you
   * implement a hot reloading mechanism for Redux.
   *
   * @param {Function} nextReducer The reducer for the store to use instead.
   * @returns {void}
   */
  function replaceReducer(nextReducer) {
    if (typeof nextReducer !== 'function') {
      throw new Error('Expected the nextReducer to be a function.')
    }

    currentReducer = nextReducer
    dispatch({ type: ActionTypes.REPLACE })
  }

替换原来的currentReducer,并派发一个Redux私有action,这个action的type是一个随机值。

看注释,可有用来做热更新。

7、230行——267行

待定。

代码语言:javascript复制
  /**
   * Interoperability point for observable/reactive libraries.
   * @returns {observable} A minimal observable of state changes.
   * For more information, see the observable proposal:
   * https://github.com/tc39/proposal-observable
   */
  function observable() {
    const outerSubscribe = subscribe
    return {
      /**
       * The minimal observable subscription method.
       * @param {Object} observer Any object that can be used as an observer.
       * The observer object should have a `next` method.
       * @returns {subscription} An object with an `unsubscribe` method that can
       * be used to unsubscribe the observable from the store, and prevent further
       * emission of values from the observable.
       */
      subscribe(observer) {
        if (typeof observer !== 'object' || observer === null) {
          throw new TypeError('Expected the observer to be an object.')
        }

        function observeState() {
          if (observer.next) {
            observer.next(getState())
          }
        }

        observeState()
        const unsubscribe = outerSubscribe(observeState)
        return { unsubscribe }
      },

      [$$observable]() {
        return this
      }
    }
  }

暂不清楚作用是什么,似乎涉及到ES6中观察者的相关概念。

8、269行——280行

初始化state树并返回之前定义的一些函数。

代码语言:javascript复制
  // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.
  dispatch({ type: ActionTypes.INIT })

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

调用createStore创建store的时候会自动派发一次action,用于初始化state树。

四、扩展点

createStore.js文件开头引用了3个模块:

  • symbol-observable:暂不清楚实际作用。(https://github.com/tc39/proposal-observable)
  • ActionTypes:里面包含3个Redux私有action,type追加了随机数。
  • isPlainObject:纯对象检查函数。

纯对象(Plain Object)指 的是通过字面量形式或者new Object()形式定义的对象。先看下这个函数:

代码语言:javascript复制
function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false

  let proto = obj
  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto)
  }

  return Object.getPrototypeOf(obj) === proto
}

这个函数很巧妙,Object.getPrototypeOf()用于返回对象的原型,在js中数组、对象、日期、正则的typeof运算结果都是object:

代码语言:javascript复制
console.log(typeof []);
console.log(typeof {});
console.log(typeof new Date());
console.log(typeof new RegExp());

js是基于原型链的,纯对象的原型是一个特殊对象,这个特殊对象没有原型的,处于最顶层:

代码语言:javascript复制
({}).__proto__.__proto__ === null; // true

而Array、RegExp的实例相对于纯对象,所处原型链的位置相对较低,所以知道了这一点,那上边的函数就好理解了。

代码语言:javascript复制
[].__proto__.__proto__.__proto__ === null; //true
new RegExp().__proto__.__proto__.__proto__ === null; //true

//或

Array.prototype.__proto__.__proto__ === null;
RegExp.prototype.__proto__.__proto__ === null;

五、总结

调用createStore用来创建一个store对象,这个store暴露了4个方法:

  1. dispatch:用于派发action
  2. subscribe:用于注册监听器回调函数
  3. getState:用于获取当前state树
  4. replaceReducer:用于替换reducer

0 人点赞