提到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中纯函数才是好函数。

谢谢大家。

redux源码解析-函数式编程的更多相关文章

  1. redux源码解析(深度解析redux+异步demo)

    redux源码解析 1.首先让我们看看都有哪些内容 2.让我们看看redux的流程图 Store:一个库,保存数据的地方,整个项目只有一个 创建store Redux提供 creatStore 函数来 ...

  2. redux源码解析-redux的架构

    redux很小的一个框架,是从flux演变过来的,尽管只有775行,但是它的功能很重要.react要应用于生成环境必须要用flux或者redux,redux是flux的进化产物,优于flux. 而且r ...

  3. Redux源码分析之bindActionCreators

    Redux源码分析之基本概念 Redux源码分析之createStore Redux源码分析之bindActionCreators Redux源码分析之combineReducers Redux源码分 ...

  4. Redux异步解决方案之Redux-Thunk原理及源码解析

    前段时间,我们写了一篇Redux源码分析的文章,也分析了跟React连接的库React-Redux的源码实现.但是在Redux的生态中还有一个很重要的部分没有涉及到,那就是Redux的异步解决方案.本 ...

  5. MyBatis源码解析【7】接口式编程

    前言 这个分类比较连续,如果这里看不懂,或者第一次看,请回顾之前的博客 http://www.cnblogs.com/linkstar/category/1027239.html 修改例子 在我们实际 ...

  6. redux的源码解析

    一. redux出现的动机 1. Javascript 需要管理比任何时候都要多的state2. state 在什么时候,由于什么原因,如何变化已然不受控制.3. 来自前端开发领域的新需求4. 我们总 ...

  7. Redux系列x:源码解析

    写在前面 redux的源码很简洁,除了applyMiddleware比较绕难以理解外,大部分还是 这里假设读者对redux有一定了解,就不科普redux的概念和API啥的啦,这部分建议直接看官方文档. ...

  8. 【Android编程】android平台的MITM瑞士军刀_cSploit源码解析及中间人攻击复现

    /文章作者:Kali_MG1937 作者博客ID:ALDYS4 QQ:3496925334 未经允许,禁止转载/ 何为MITM欺骗,顾名思义,中间人攻击的含义即为在局域网中充当数据包交换中间人的角色 ...

  9. redux源码解读

    react在做大型项目的时候,前端的数据一般会越来越复杂,状态的变化难以跟踪.无法预测,而redux可以很好的结合react使用,保证数据的单向流动,可以很好的管理整个项目的状态,但是具体来说,下面是 ...

随机推荐

  1. Linux基础学习笔记2-文件管理和重定向

    本节内容 1)文件系统结构元素 2)创建和查看文件 3)复制.转移和删除文件 4)软和硬链接 5)三种I/O设备 6)把I/O重定向至文件 7)使用管道 文件系统和结构 文件系统 文件和目录被组织成一 ...

  2. 安装splash

    参考: https://blog.csdn.net/qq_41020281/article/details/82599075

  3. MBG逆向工程报错:generate failed: Exception getting JDBC Driver: com.mysql.jdbc.Driver

    修改pom文件,逆向工程如下: <!-- 逆向工程 --> <plugin> <groupId>org.mybatis.generator</groupId& ...

  4. Java之XML操作:从XML中直接获取数据

    本文介绍如何将数据记录在XML文件中,然后通过DOM4J直接从XML中读取到数据. 依赖包: <dependency> <groupId>dom4j</groupId&g ...

  5. extensions

    extensions.blocklist.enabled

  6. codeforces158D

    Ice Sculptures CodeForces - 158D The Berland University is preparing to celebrate the 256-th anniver ...

  7. 洛谷 P1160 队列安排

    题目描述 一个学校里老师要将班上 NNN 个同学排成一列,同学被编号为 $1-N$ ,他采取如下的方法: 先将 111 号同学安排进队列,这时队列中只有他一个人: 2−N2-N2−N 号同学依次入列, ...

  8. js判断一个元素是否在数组中

    js判断一个元素是否在数组中 var arr = ['a','s','d','f']; console.info(isInArray(arr,'a'));//循环的方式 function isInAr ...

  9. POJ 3264-Balanced Lineup-RMQ问题

    裸RMQ问题 #include <cstdio> #include <algorithm> #include <cstring> using namespace s ...

  10. hdu 2191 (多重背包二进制优化)

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=2191 实现代码: #include<bits/stdc++.h> using namespac ...