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

      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.push(listener);    //把这个监听加到下个监听事件

        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;   //处理完state以后执行所有注册的监听函数
        for (var i = 0; i < listeners.length; i++) {
          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。

接下来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中纯函数才是好函数。

谢谢大家。

时间: 2024-10-27 20:10:44

redux源码解析,函数式编程的相关文章

redux源码解析-redux的架构

redux很小的一个框架,是从flux演变过来的,尽管只有775行,但是它的功能很重要.react要应用于生成环境必须要用flux或者redux,redux是flux的进化产物,优于flux. 而且redux还很小.那么redux是怎么做到单项数据流和一些让人惊奇的特性的呢.我们来看一下他的源码,从而学一些东西. redux里面都是一个一个的模块,一共9个模块,都导出了一些redux的方法,比如这个9,一个匿名函数,然后导出他写的方法.9里面就这一个方法.英文注释也蛮清楚的,检测类对象的方法.

6、redux源码解析 - 中间件源码剖析

//源码使用方法 import {createStore, applyMiddleWare} from 'redux'; //createStore.js的源码 export default function createStore(reducer, preloadState, enhancer) { //... if(typeof enhancer !== 'undefined'){ if(typeof enhancer !== 'function'){ throw new Error('..

4、redux源码解析 - 糅合多种dispatch

在开发时,也许需要更多地包装dispatch以实现更加完善的功能.比如包装 dispatch来打印日志,包装dispatch以支持Promise,各种包装需要密切配合. 之前两篇代码的汇总: //包装dispatch来打印日志 const addLoggingToDispatch = (store) => { const rawDispatch = store.dispatch; if(!console.group){ return rawDispatch; } return (action)

68:Scala并发编程原生线程Actor、Cass Class下的消息传递和偏函数实战解析及其在Spark中的应用源码解析

今天给大家带来的是王家林老师的scala编程讲座的第68讲:Scala并发编程原生线程Actor.Cass Class下的消息传递和偏函数实战解析 昨天讲了Actor的匿名Actor及消息传递,那么我们今天来看一下原生线程Actor及CassClass下的消息传递,让我们从代码出发: case class Person(name:String,age:Int)//定义cass Class class HelloActor extends Actor{//预定义一个Actor  def act()

Linux内核编程:Linux2.6内核源码解析_进程遍历 &nbsp; &nbsp; &nbsp; &nbsp;

/*     *File    : test.c   *Author  : DavidLin        *Date    : 2014-12-07pm        *Email   : [email protected] or [email protected]        *world   : the city of SZ, in China        *Ver     : 000.000.001        *history :     editor      time    

Redux系列x:源码解析

写在前面 redux的源码很简洁,除了applyMiddleware比较绕难以理解外,大部分还是 这里假设读者对redux有一定了解,就不科普redux的概念和API啥的啦,这部分建议直接看官方文档. 此外,源码解析的中文批注版已上传至github,可点击查看.本文相关示例代码,可点击查看. 源码解析概览 将redux下载下来,然后看下他的目录结构. npm install redux 这里我们需要关心的主要是src目录,源码解析需要关心的文件都在这里面了 index.js:redux主文件,主

Android网络编程(十一)源码解析Retrofit

相关文章 Android网络编程(一)HTTP协议原理 Android网络编程(二)HttpClient与HttpURLConnection Android网络编程(三)Volley用法全解析 Android网络编程(四)从源码解析volley Android网络编程(五)OkHttp2.x用法全解析 Android网络编程(六)OkHttp3用法全解析 Android网络编程(七)源码解析OkHttp前篇[请求网络] Android网络编程(八)源码解析OkHttp后篇[复用连接池] Andr

Android网络编程(七)源码解析OkHttp前篇[请求网络]

相关文章 Android网络编程(一)HTTP协议原理 Android网络编程(二)HttpClient与HttpURLConnection Android网络编程(三)Volley用法全解析 Android网络编程(四)从源码解析volley Android网络编程(五)OkHttp2.x用法全解析 Android网络编程(六)OkHttp3用法全解析 前言 学会了OkHttp3的用法后,我们当然有必要来了解下OkHttp3的源码,当然现在网上的文章很多,我仍旧希望我这一系列文章篇是最简洁易懂

redux教程之源码解析createStore

redux源码 redux的源码很简单,分为以下几部分 createStore combineReducers applyMiddleware compose bindActionCreators createStore即入口函数生成store,将reducer和middleware关联起来 combineReducers即将分散的reducer最终合并成一个统一的reducer applyMiddleware即将多个中间件一次合并到reducer中,生成一个最终的reducer compose