react-redux源码解析
有理解不对的地方,欢迎大家指正!!!
react为什么需要redux辅助???react是view层的单向数据流框架,数据需要一层一层往子组件传递(子组件并不会自动继承)。子组件需要操作父组件的数据时,需要父组件给子组件传递一个方法,子组件调用该方法才能改变父组件的数据。如果组件的层次太深会这种传递会很繁琐,令代码沉余。用redux能很好解决这个问题,redux+react-redux可以使一个容器内的数据通过this.props共享,避免了一层层传递数据繁琐的操作。
redux使用了纯函数写法,这种编程模式就是函数式编程(简称:fb)。
redux主要分为三部分:store,actions,reducer;
store:有三个主要方法(dispatch、subscribe、getState);
1.createStore(reducer,initState)创建一个store树
2.subscribe监听事件,执行查询操作时需要做的其他事情
3.dispatch发布事件,主要负责执行监听的事件队列与执行查询数据操作
4.getState获取查询的结果
action:相当于一个小型的数据库,保存需要操作的数据。以action.type做主键,每条数据都使用函数包裹保证独立的作用域,通过reducer查询数据写入store;
定义action里面的数据如下:
export let add=function(){
return {
type:"ADD",
}
}
export let cut=function(){
return {
type:"CUT",
}
}
export let getValue=function(value){
return {
type:"VALUE",
value:value,
}
}
reducer:主要负责筛选查询的数据更新给store,reducer一般用switch实现,但是redux本身没有这种要求。用状态模式来完成这项任务会更加完美:
function(state,action){
var data={
"ADD":{
value:state.value+1,
},
"CUT":{
value:state.value-1,
},
"VALUE":{
value:action.value,
},
"DEFAULT":{
value:0,
}
}
return data[action.type||"DEFAULT"];
}
这种写法是不是更直观呢???
rudex使用了大量的设计模式比较,如:装饰者模式(包装),工厂模式,桥接模式,代理模式,观察者模式。
装饰者模式:包装的action、dispatch、createStore,扩展本身,满足需求,不改变原有的代码;
工厂模式:action包装器也是一个工厂,通过该方法生产新的action;
代理模式:applyMiddleware返回一个方法(该方法就是个代理)取需要的createStore方法;
桥接模式:isPlainObject通过连接isHostObject与isObjectLike方法来完成新的验证功能;
观察者模式:通过subscribe添加监听事件队列,dispatch执行事件队列与更新state;
模块1:模块1并没有什么好介绍的,主体就一个compose方法为模块5的applyMiddleware方法服务,作用是把applyMiddleware的参数串联执行,最后返回包装的dispatch。
/* 1 */ /***/ 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))). */ //compose为模块5的applyMiddleware方法服务,把applyMiddleware的参数串联执行返回包装的dispatch function compose() { //复制参数 for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; }return function () { if (funcs.length === 0) { return arguments.length <= 0 ? undefined : arguments[0]; } var last = funcs[funcs.length - 1]; //最后一个参数 var rest = funcs.slice(0, -1); //除了最后一个参数外的所有参数 //从右到左串联执行rest参数列表里的方法 return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); } /***/ },
模块2:主体createStore方法,createStore方法里主要包括:subscribe--订阅事件,dispatch---发布事件,getState---获取状态
其实他们做的事都很简单:subscribe把接受方法(事件)push(入栈)进一个数组,dispatch被调用时则依次执行数组里的方法
/* 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' }; //创建store树 function createStore(reducer, initialState, enhancer) { //参数匹配 if (typeof initialState === 'function' && typeof enhancer === 'undefined') { enhancer = initialState; initialState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } //enhancer对createStore进行扩展 return enhancer(createStore)(reducer, initialState); } if (typeof reducer !== 'function') { 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(); } } //获取state function getState() { return currentState; } //订阅事件 function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } //保证事件只能被卸载一次 var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); //闭包缓存正在监听的事件,可以通过:var unsub=subscribe(listener); unsub()来卸载此事件 return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; //备份事件队列再进行卸载操作 ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } //发布事件 function dispatch(action) { //检测action是否是字面量对象 if (!(0, _isPlainObject2["default"])(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; //执行reducer更新state currentState = currentReducer(currentState, action); } finally { isDispatching = false; } //同步事件队列---执行最新的事件队列 var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } //替换reducer function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } //初始化state dispatch({ type: ActionTypes.INIT }); return { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }; } /***/ }, 模块4:模块3很简单就此跳过,咱们进入模块4。模块4也比较简单主体:isPlainObject方法主要是检测是否是字面量对象或者是直接实例化Object构造函数的实例对象
/* 4 */ /***/ function(module, exports, __webpack_require__) { var isHostObject = __webpack_require__(8), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var getPrototypeOf = Object.getPrototypeOf; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * 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 */ //判断是否由Object直接构造出来的实例 function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = objectProto; if (typeof value.constructor == 'function') { proto = getPrototypeOf(value); } //参数的构造函数时function且原型是null if (proto === null) { return true; } var Ctor = proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } module.exports = isPlainObject; /***/ },
模块5:此模块的逻辑比较复杂,但是实现的东西却很简单:包装了createStore方法与createStore里的dispatch方法,使dispath支持异步。 applyMiddleware参数是redux提供的两个中间件:redux-thunks、redux-logger,两个中间件提供方法对dispatch进行包装。
/* 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 }; } //包装createStore与dispatch function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { //返回一个包装的createStore return function (reducer, initialState, enhancer) { var store = createStore(reducer, initialState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; //34-38行的代码原型:thunkMiddleware(middlewareAPI)(createLogger()(middlewareAPI)(dispatch))返回被包装的dispatch。thunkMiddleware与createLogger分别是redux-thunks、redux-logger中间件提供的 chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }) _dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch); //将包装好的dispatch写入store return _extends({}, store, { dispatch: _dispatch }); }; }; }
对dispatch进行了怎样的包装呢???其实只是添加了一条判断语句,这条判断语句有什么作用?很简单!如果是方法则执行该方法,否则执行dispath更新state。
为什么需要这样做?因为当你在action存放一些不需要立即更新state的动作(如异步请求),单纯的action是无法满足的(因为dispatch后就会马上更新state),
所以需要对dispatch进行包装。包装后怎么使用dispath呢?之前的功能一样可以使用,需要用到异步的时候你可以返回一个方法,在这个方法里面执行真正的dispatch
可以这样定义action里的方法如:
export let add=function(){
return {
type:"ADD",
}
}
export let request=function(){
return function(dispatch){
$.ajax({
type:"post",
url:"baidu.com",
success:function(){
dispatch(action());
}
})
}
}
redux-thunks模块里的thunkMiddleware方法源码:
function thunkMiddleware(_ref) { var dispatch = _ref.dispatch; var getState = _ref.getState; //next===createLogger()(middlewareAPI)(dispatch)执行了这个方法 return function (next) { //返回一个包装的dispacth return function (action) { if (typeof action === 'function') { return action(dispatch, getState); } return next(action); //由于闭包next一直存在于包装的dispatch里,next其实是一个普通的dispatch,虽然经过了createLogger方法(redux-logger里面内置的一个方法)的包装, 但是主要作用与createStore定义时的dispatch方法是一样的 }; }; }
模块6:把action与dispatch方法绑定在一起,即把每个action包装着一个dispatch方法,然后执行action时就会自动dispath
/* 6 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports["default"] = bindActionCreators; //包装器---返回一个自动执行dispatch的方法 function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { 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]; if (typeof actionCreator === 'function') { //收集包装器返回的新的action方法 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; }
模块7:执行reducers返回state
/* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports["default"] = combineReducers; var _createStore = __webpack_require__(2); var _isPlainObject = __webpack_require__(4); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(3); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2["default"])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key); }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } //初始化reducers并检测时候会出错 function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; //过滤参数---把reducers里的方法放进finalReducers for (var i = 0; i < reducerKeys.length; i++) { 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; } //把state,action分发给每一个reducer,并执行返回新的state,如果state没变化则返回原来的state return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; 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++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key];//获取一个reducer方法 var previousStateForKey = state[key]; //获取上次的state var nextStateForKey = reducer(previousStateForKey, action);//执行reducer if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey;//判断上次的state与现在的state是否相等 } return hasChanged ? nextState : state; }; }
模块8:检测ie9以下的宿主对象,即dom与bom,就不上源码了
模块9:检测是否是对象
总结一下:
redux是不是很简单?就那么几个方法:createStore,subscribe,dispatch,getState,applyMiddleware,bindActionCreators,combineReducers。
createStore:创建store树;
createStore->subscribe:订阅事件,把监听的执行的方法放进来,其实就是一个数组;
createStore->dispatch:发布,执行所有的监听事件,且执行reducer更新state;
createStore->getState:获取state;
applyMiddleware:包装createStore与dispatch;
bindActionCreators:包装所有的action方法,给每个action包装一个dispatch方法,使执行action方法就会自动触发dispatch方法
combineReducers:合并多个reducer;
react-redux源码解析的更多相关文章
- redux源码解析(深度解析redux+异步demo)
redux源码解析 1.首先让我们看看都有哪些内容 2.让我们看看redux的流程图 Store:一个库,保存数据的地方,整个项目只有一个 创建store Redux提供 creatStore 函数来 ...
- React的React.createContext()源码解析(四)
一.产生context原因 从父组件直接传值到孙子组件,而不必一层一层的通过props进行传值,相比较以前的那种传值更加的方便.简介. 二.context的两种实现方式 1.老版本(React16.x ...
- React的React.createElement源码解析(一)
一.什么是jsx jsx是语法糖 它是js和html的组合使用 二.为什么用jsx语法 高效定义模版,编译后使用 不会带来性能问题 三.jsx语法转化为js语法 jsx语法通过babel转化为 ...
- redux源码解析-redux的架构
redux很小的一个框架,是从flux演变过来的,尽管只有775行,但是它的功能很重要.react要应用于生成环境必须要用flux或者redux,redux是flux的进化产物,优于flux. 而且r ...
- redux源码解析-函数式编程
提到redux,会想到函数式编程.什么是函数式编程?是一种很奇妙的函数式的编程方法.你会感觉函数式编程这么简单,但是用起来却很方便很神奇. 在<functional javascript> ...
- React的React.createRef()/forwardRef()源码解析(三)
1.refs三种使用用法 1.字符串 1.1 dom节点上使用 获取真实的dom节点 //使用步骤: 1. <input ref="stringRef" /> 2. t ...
- Redux源码分析之bindActionCreators
Redux源码分析之基本概念 Redux源码分析之createStore Redux源码分析之bindActionCreators Redux源码分析之combineReducers Redux源码分 ...
- Redux系列x:源码解析
写在前面 redux的源码很简洁,除了applyMiddleware比较绕难以理解外,大部分还是 这里假设读者对redux有一定了解,就不科普redux的概念和API啥的啦,这部分建议直接看官方文档. ...
- Redux异步解决方案之Redux-Thunk原理及源码解析
前段时间,我们写了一篇Redux源码分析的文章,也分析了跟React连接的库React-Redux的源码实现.但是在Redux的生态中还有一个很重要的部分没有涉及到,那就是Redux的异步解决方案.本 ...
- redux的源码解析
一. redux出现的动机 1. Javascript 需要管理比任何时候都要多的state2. state 在什么时候,由于什么原因,如何变化已然不受控制.3. 来自前端开发领域的新需求4. 我们总 ...
随机推荐
- Scut:GameWebSocketHost 解析
想使用 Scut 做的是一个短连接项目,所以先直接看 GameWebSocketHost 了. 先来看下 GameWebSocketHost 的成员: protected bool EnableHtt ...
- Watchcow
传送门 题目大意: 给你一幅连通的图,要求从起点1开始走,要经过每条边刚好两次,并且最终回到1起点. 思路:将无向图转换成有向图求欧拉回路. #include<cstdio> #defin ...
- beini系列_1_U盘引导制作
奶瓶(beini)这个系统,是一款基于 Tiny Core Linux 搭建的无线网络安全测试系统,当然由于它是用来安全测试的系统,因此在安全方面自然有着强大的功能.而且,这个系统非常简便易学,因此现 ...
- Java进阶代码
本文重在温习……不过初学以及进阶高手不可错过 1. public static void arraycopy(全小写)(object src,int srcPos,object dest,int d ...
- Sequence
http://poj.org/problem?id=2442 用STL写的时间为:5657MS #include<cstdio> #include<algorithm> #in ...
- eclipse能够自动提示变量名.
打开 Eclipse -> Window -> Perferences -> Java -> Editor -> Content Assist,在右边最下面一栏找到 au ...
- 14.4.4 Redo Log Buffer
14.4.4 Redo Log Buffer redo log buffer 是内存区域持有数据被写入到redo log. Redo log buffer size 是通过 innodb_log_bu ...
- 最小费用最大流MCMF zkw费用流
稀疏图慢死了...但是稠密图效果还是很好的 struct MCMF{ struct tedge{int x,y,cap,w,next;}adj[maxm];int ms,fch[maxn]; int ...
- fastjson将bean转成字符串时首字母变小写问题
一个项目需求要求返回值为JSON格式,且大多数字段是首字母大写,还有些是类似N_TX这样的格式,在输出这样的结果时遇到了问题,由于时间紧,就直接拷贝需要的结果字段建立JavaBean类,本以为最后直接 ...
- 基于deb包快速搭建内外apt源