redux源碼解析-函數式編程


 提到redux,會想到函數式編程。什么是函數式編程?是一種很奇妙的函數式的編程方法。你會感覺函數式編程這么簡單,但是用起來卻很方便很神奇。

在《functional javascript》中,作者批評了java那種任何東西都用對象來寫程序的方式,提倡了這種函數式編程。

之前看過一些函數式編程的例子(以下簡稱fp)。提到fp會想到underscore和lodash,你會看到lodash的包中,唯一一個文件夾就是fp,里面是fp相關的函數。

在redux中,也是運用了很多fp的函數。其實在寫js中經常用到fp,但是你不清楚。比如ajax的callback即是一種fp的思想。 

接上文(點此飛到上文:redux的架構),redux的一號函數,一個fp的經典函數,組合函數:(復制此函數直接測試)

 function(module, exports) {

    "use strict";

    exports.__esModule = true;
    exports["default"] = compose;
    /**
     * Composes single-argument functions from right to left.
     *
     * @param {...Function} funcs The functions to compose.
     * @returns {Function} A function obtained by composing functions from right to
     * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
     */
    function compose() {
      for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { 
        funcs[_key] = arguments[_key]; //把所有參數都復制到funcs數組里
      }

      return function () {
        if (funcs.length === 0) {
          return arguments.length <= 0 ? undefined : arguments[0];
        }  //如果沒有參數返回undefined

        var last = funcs[funcs.length - 1];  //最后一個參數
        var rest = funcs.slice(0, -1);   //剩下的前幾個參數

        return rest.reduceRight(function (composed, f) {
          return f(composed);
        }, last.apply(undefined, arguments));  //執行最后一個參數並且把返回值交給下前一個參數。  
      };                                       //當然,想改變順序也可以不用reduceRight換為reduce
    } 

 },

比如compose(f, g, h)就會這樣執行=> f(g(h(arg)))。這個函數的簡化版就是這樣:

var compose = function(f,g) {
  return function(x) {
    return f(g(x));
  };
};

但是這函數不支持多參數。我們看看那里用到了這個函數,直接跳到5號函數:

 function(module, exports, __webpack_require__) {

    'use strict';

    var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

    exports.__esModule = true;
    exports["default"] = applyMiddleware;

    var _compose = __webpack_require__(1);

    var _compose2 = _interopRequireDefault(_compose);

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

    /**
     * Creates a store enhancer that applies middleware to the dispatch method
     * of the Redux store. This is handy for a variety of tasks, such as expressing
     * asynchronous actions in a concise manner, or logging every action payload.
     *
     * See `redux-thunk` package as an example of the Redux middleware.
     *
     * Because middleware is potentially asynchronous, this should be the first
     * store enhancer in the composition chain.
     *
     * Note that each middleware will be given the `dispatch` and `getState` functions
     * as named arguments.
     *
     * @param {...Function} middlewares The middleware chain to be applied.
     * @returns {Function} A store enhancer applying the middleware.
     */
    function applyMiddleware() {
      for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { //跟compose一樣處理參數
        middlewares[_key] = arguments[_key];
      }

      return function (createStore) {
        return function (reducer, initialState, enhancer) {
          var store = createStore(reducer, initialState, enhancer);//傳入createStore方法
          var _dispatch = store.dispatch;            //重要的dispatch方法
          var chain = [];

          var middlewareAPI = {            //需要傳入middleware的reduxAPI
            getState: store.getState,
            dispatch: function dispatch(action) {
              return _dispatch(action);
            }
          };
          chain = middlewares.map(function (middleware) {  //遍歷每個中間件把reduxAPI傳進去。返回一個封裝好的中間件
            return middleware(middlewareAPI);
          });
          _dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch);  //相當於compose(...chain)(store.dispatch)

          return _extends({}, store, {    //然后給store重寫的這個執行完中間件的dispatch方法。
            dispatch: _dispatch
          });
        };
      };
    }

看到導入的方法了嗎,var _compose = __webpack_require__(1);然后在redux的applyMiddleware用到了這個compose。

我們回想一下applyMiddleware是干什么用的----使用包含自定義功能的 middleware 來擴展 Redux 是一種推薦的方式。Middleware 可以讓你包裝 store 的dispatch方法來達到你想要的目的。同時, middleware 還擁有“可組合”這一關鍵特性。多個 middleware 可以被組合到一起使用,形成 middleware 鏈。其中,每個 middleware 都不需要關心鏈中它前后的 middleware 的任何信息。

其中用的最多的就是thunkmiddleware。其實thunk也是fp的一種。。。這里不多說了。看這個applyMiddleware怎么調用呢?

createStore這個函數在別的模塊先不說,thunk是redux-thunk導出的函數。它的compose函數做了什么?

參數是封裝好的中間件,利用apply傳入,利用compose挨個執行,執行順序從右到左。並傳入dispatch給它用。

圖上只有一個中間件thunk,執行完  return function (reducer, initialState, enhancer) {},下面又傳入了reducer,就開始執行這個函數了,需要傳入middleware的reduxAPI,執行中間件傳入dispatch,到最后返回一個重寫dispatch的store,也就是圖上這個store。這個store到底是什么?這得看一下var store = createStore(reducer, initialState, enhancer);這句的createStore方法。

這樣2個模塊就介紹完了。是不是so easy。

回到我們的2號函數。超級長。就是我們的createStore。是整個redux的最重要的部分。

 模塊2里面用到了模塊4,簡單介紹一下:

解釋為Checks if `value` is a plain object, that is, an object created by the `Object` constructor or one with a `[[Prototype]]` of `null`.

檢查一個對象是不是plain object,就是由Object構造的或者[[Prototype]]屬性是null的對象。比如

function Foo() {
      this.a = 1;
}
    
_.isPlainObject(new Foo);
// => false
    
 _.isPlainObject([1, 2, 3]);
// => false
     
 _.isPlainObject({ 'x': 0, 'y': 0 });
 // => true
     
 _.isPlainObject(Object.create(null));
 // => true

函數和數組都不是,對象會返回true。好模塊4就講完了。

回到模塊2,看注釋就能明白這些函數的作用。

function(module, exports, __webpack_require__) {

    'use strict';

    exports.__esModule = true;
    exports.ActionTypes = undefined;
    exports["default"] = createStore;

    var _isPlainObject = __webpack_require__(4);

    var _isPlainObject2 = _interopRequireDefault(_isPlainObject);

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

    /**
     * These are private action types reserved by Redux.
     * For any unknown actions, you must return the current state.
     * If the current state is undefined, you must return the initial state.
     * Do not reference these action types directly in your code.
     */
    var ActionTypes = exports.ActionTypes = {
      INIT: '@@redux/INIT'
    };

    /**
     * Creates a Redux store that holds the state tree.
     * The only way to change the data in the store is to call `dispatch()` on it.
     *
     * There should only be a single store in your app. To specify how different
     * parts of the state tree respond to actions, you may combine several reducers
     * into a single reducer function by using `combineReducers`.
     *
     * @param {Function} reducer A function that returns the next state tree, given
     * the current state tree and the action to handle.
     *
     * @param {any} [initialState] The initial state. You may optionally specify it
     * to hydrate the state from the server in universal apps, or to restore a
     * previously serialized user session.
     * If you use `combineReducers` to produce the root reducer function, this must be
     * an object with the same shape as `combineReducers` keys.
     *
     * @param {Function} enhancer The store enhancer. You may optionally specify it
     * to enhance the store with third-party capabilities such as middleware,
     * time travel, persistence, etc. The only store enhancer that ships with Redux
     * is `applyMiddleware()`.
     *
     * @returns {Store} A Redux store that lets you read the state, dispatch actions
     * and subscribe to changes.
     */
    function createStore(reducer, initialState, enhancer) {
      if (typeof initialState === 'function' && typeof enhancer === 'undefined') { //判斷初始store不能是函數,如果是函數
        enhancer = initialState;                                            //傳給enhancer
        initialState = undefined;
      }

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

        return enhancer(createStore)(reducer, initialState);            //傳給enhancer之后先調用enhancer,傳入createStore,然后
      }                                                                    //給它參數,這個函數參數是createStore,所以這個enhancer隨便傳是不行的。里面的邏輯要自己處理reducer和initialState
                                          //有一種用法是:

                                             //const store = createStore(reducer, initialState, compose(
                                              // applyMiddleware(thunk),
                                             // window.devToolsExtension ? window.devToolsExtension() : f => f

                                             // })

                                             //把applyMiddleware和redux devTools組合起來放到第三個參數,可以這樣用就是因為在createStore里面會傳給第三個參數傳自身和reducer,store這些來操作store
));

      if (typeof reducer !== 'function') {                           //reducer必須是個函數
        throw new Error('Expected the reducer to be a function.');
      }

      var currentReducer = reducer;                    
   var currentState = initialState; var currentListeners = []; //當前監聽事件列表 var nextListeners = currentListeners;   //注意這里是等號
var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { //如果監聽序列等於當前序列,這里的等號是判斷引用是否相同 nextListeners = currentListeners.slice(); //復制一份當前監聽序列 }                             } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { //重要的getState方法,只是返回了currentState return currentState; } /** * 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 states 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) { //redux的subscribe方法 if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); //保證修改nextListeners不會改了currentListeners nextListeners.push(listener); //把這個監聽加到復制過的監聽事件列表,這樣nextListeners就和currentListeners不同了。 return function unsubscribe() { //跟許多事件系統一樣,返回一個取消事件綁定的函數 if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); //找一下剛才注冊函數,然后刪掉。 nextListeners.splice(index, 1); }; } /** * 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 (!(0, _isPlainObject2["default"])(action)) { //用到模塊4的函數。這個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); //主要是這句,把當前的state經過reducer處理 } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; //當前監聽列表變為修改過的nextListeners for (var i = 0; i < listeners.length; i++) { //處理完state以后執行所有注冊過的監聽函數 listeners[i](); } return action; } /** * 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; //代替當前reducer dispatch({ type: ActionTypes.INIT }); } // 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 }); //觸發一個內部dispatch return { //這是store導出的方法。剛剛模塊2返回也重寫了dispatch,但是應該沒有改變 dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }; }

這樣大家就大概明白store了,注冊監聽函數,dispatch,經過reducer處理,然后觸發監聽函數,最后返回該store。

這里值得注意的是 ensureCanMutateNextListeners函數和nextListeners和currentListeners。

nextListeners僅是currentListeners的一個引用。這樣經過ensureCanMutateNextListeners肯定是全等(===)的,然后nextListeners成為了currentListeners的一個復制。后來處理的都是這個nextListeners。

那么為什么要寫兩個listeners呢?

情況1,當監聽器里面如果有subscribe或unsubscribe,如果操作一個listeners,就會循環修改listeners,執行順序是不是一團糟?

那么怎么保證順序呢?

var listeners = currentListeners = nextListeners;

這個listeners不會變,為什么呢,每次修改都修改nextListeners對嗎,然而在每次在執行監聽或者取消監聽的時候,是不是都會執行那個復制函數?這樣nextListeners會被修改,這時他已經脫離這個三等式了,這個listeners就不變了,執行順序也就保證了。

如果沒有上面情況1的話,每次都復制一遍的話那不就白slice()了?

所以它用了這個函數ensureCanMutateNextListeners,每次只在添加監聽或者取消監聽的時候復制當前監聽列表,那損失就會降到最低了吧~

接下來3號函數

沒什么。導出一個warning函數,做警告用。

函數6號呢,寫了bindActionCreators,這個redux的方法。我們看一下源碼。

function(module, exports) {

    'use strict';

    exports.__esModule = true;
    exports["default"] = bindActionCreators;
    function bindActionCreator(actionCreator, dispatch) {
      return function () {
        return dispatch(actionCreator.apply(undefined, arguments)); //把actionCreator封裝一層dispatch,就像我在初入redux的時候說的,
                                                                    //省的在組件里dispatch,麻煩也不好看。
      };
    }

    /**
     * Turns an object whose values are action creators, into an object with the
     * same keys, but with every function wrapped into a `dispatch` call so they
     * may be invoked directly. This is just a convenience method, as you can call
     * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
     *
     * For convenience, you can also pass a single function as the first argument,
     * and get a function in return.
     *
     * @param {Function|Object} actionCreators An object whose values are action
     * creator functions. One handy way to obtain it is to use ES6 `import * as`
     * syntax. You may also pass a single function.
     *
     * @param {Function} dispatch The `dispatch` function available on your Redux
     * store.
     *
     * @returns {Function|Object} The object mimicking the original object, but with
     * every action creator wrapped into the `dispatch` call. If you passed a
     * function as `actionCreators`, the return value will also be a single
     * function.
     */
    function bindActionCreators(actionCreators, dispatch) {
      if (typeof actionCreators === 'function') {  //做一些判斷,actionCreators是函數的時候就封裝一層dispatch
        return bindActionCreator(actionCreators, dispatch);
      }

      if (typeof actionCreators !== 'object' || actionCreators === null) {
        throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
      }
        //是對象的時候
      var keys = Object.keys(actionCreators);  
      var boundActionCreators = {}; 
      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var actionCreator = actionCreators[key];  //把這個對象里的每一項都遍歷一下,只要是函數就封裝一層dispatch
        if (typeof actionCreator === 'function') {
          boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
        }
      }
      return boundActionCreators; //返回這個封裝完dispatch的這個對象。
    }

},

給ActionCreators封裝一層dispatch,也簡單。

7號函數:主要是combineReducers方法。

function combineReducers(reducers) {
      var reducerKeys = Object.keys(reducers);
      var finalReducers = {};
      for (var i = 0; i < reducerKeys.length; i++) { //遍歷所有reducers,把是函數的reducers放到finalReducers里,為了防止reducer不是函數
        var key = reducerKeys[i];
        if (typeof reducers[key] === 'function') {
          finalReducers[key] = reducers[key];
        }
      }
      var finalReducerKeys = Object.keys(finalReducers);

      var sanityError;
      try {
        assertReducerSanity(finalReducers);
      } catch (e) {
        sanityError = e;
      }

      return function combination() {
        var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];//reducer當然是傳state進來再返回新state,這里就是傳入的state
        var action = arguments[1];//第二個參數是action

        if (sanityError) {
          throw sanityError;
        }

        if (true) {
          var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action);
          if (warningMessage) {
            (0, _warning2["default"])(warningMessage);
          }
        }

        var hasChanged = false;
        var nextState = {};
        for (var i = 0; i < finalReducerKeys.length; i++) { //遍歷所有reducers,讓他們都處理一次state
          var key = finalReducerKeys[i];
          var reducer = finalReducers[key];        //從reducers中取出一個reducer
          var previousStateForKey = state[key]; //改變之前的state
          var nextStateForKey = reducer(previousStateForKey, action);//state經過reducer處理后的state
          if (typeof nextStateForKey === 'undefined') {
            var errorMessage = getUndefinedStateErrorMessage(key, action);
            throw new Error(errorMessage);
          }
          nextState[key] = nextStateForKey;  //改變后的state保存到nextState里
          hasChanged = hasChanged || nextStateForKey !== previousStateForKey; //判斷state改變沒
        }
        return hasChanged ? nextState : state;    //要是不變就返回原來的state不然返回新state
      };
    }

組合了reducer,原理也簡單,遍歷一下剔除不是函數的reducer,讓他們都處理一下state,返回新state

最后一個,8號函數

這是檢測這個對象是不是ie9-的host obj。原理就是許多這種對象沒有toString方法,但是可以轉化為字符串。

現在所有都講完了,是不是覺得看源碼也沒那么難,redux的方法實現很簡單,而且都是純函數,你看reducer處理的時候不是改變state而是返回新state。這就保證了函數的”純“,在fp中純函數才是好函數。

謝謝大家。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM