react-redux源码解析
有理解不對(duì)的地方,歡迎大家指正!!!
react為什么需要redux輔助???react是view層的單向數(shù)據(jù)流框架,數(shù)據(jù)需要一層一層往子組件傳遞(子組件并不會(huì)自動(dòng)繼承)。子組件需要操作父組件的數(shù)據(jù)時(shí),需要父組件給子組件傳遞一個(gè)方法,子組件調(diào)用該方法才能改變父組件的數(shù)據(jù)。如果組件的層次太深會(huì)這種傳遞會(huì)很繁瑣,令代碼沉余。用redux能很好解決這個(gè)問題,redux+react-redux可以使一個(gè)容器內(nèi)的數(shù)據(jù)通過this.props共享,避免了一層層傳遞數(shù)據(jù)繁瑣的操作。
redux使用了純函數(shù)寫法,這種編程模式就是函數(shù)式編程(簡稱:fb)。
redux主要分為三部分:store,actions,reducer;
store:有三個(gè)主要方法(dispatch、subscribe、getState);
1.createStore(reducer,initState)創(chuàng)建一個(gè)store樹
2.subscribe監(jiān)聽事件,執(zhí)行查詢操作時(shí)需要做的其他事情
3.dispatch發(fā)布事件,主要負(fù)責(zé)執(zhí)行監(jiān)聽的事件隊(duì)列與執(zhí)行查詢數(shù)據(jù)操作
4.getState獲取查詢的結(jié)果
action:相當(dāng)于一個(gè)小型的數(shù)據(jù)庫,保存需要操作的數(shù)據(jù)。以action.type做主鍵,每條數(shù)據(jù)都使用函數(shù)包裹保證獨(dú)立的作用域,通過reducer查詢數(shù)據(jù)寫入store;
定義action里面的數(shù)據(jù)如下:
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:主要負(fù)責(zé)篩選查詢的數(shù)據(jù)更新給store,reducer一般用switch實(shí)現(xiàn),但是redux本身沒有這種要求。用狀態(tài)模式來完成這項(xiàng)任務(wù)會(huì)更加完美:
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使用了大量的設(shè)計(jì)模式比較,如:裝飾者模式(包裝),工廠模式,橋接模式,代理模式,觀察者模式。
裝飾者模式:包裝的action、dispatch、createStore,擴(kuò)展本身,滿足需求,不改變?cè)械拇a;
工廠模式:action包裝器也是一個(gè)工廠,通過該方法生產(chǎn)新的action;
代理模式:applyMiddleware返回一個(gè)方法(該方法就是個(gè)代理)取需要的createStore方法;
橋接模式:isPlainObject通過連接isHostObject與isObjectLike方法來完成新的驗(yàn)證功能;
觀察者模式:通過subscribe添加監(jiān)聽事件隊(duì)列,dispatch執(zhí)行事件隊(duì)列與更新state;
模塊1:模塊1并沒有什么好介紹的,主體就一個(gè)compose方法為模塊5的applyMiddleware方法服務(wù),作用是把a(bǔ)pplyMiddleware的參數(shù)串聯(lián)執(zhí)行,最后返回包裝的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方法服務(wù),把a(bǔ)pplyMiddleware的參數(shù)串聯(lián)執(zhí)行返回包裝的dispatch
function compose() {
//復(fù)制參數(shù)
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]; //最后一個(gè)參數(shù)
var rest = funcs.slice(0, -1); //除了最后一個(gè)參數(shù)外的所有參數(shù) //從右到左串聯(lián)執(zhí)行rest參數(shù)列表里的方法
return rest.reduceRight(function (composed, f) {
return f(composed);
}, last.apply(undefined, arguments));
}
/***/ },
模塊2:主體createStore方法,createStore方法里主要包括:subscribe--訂閱事件,dispatch---發(fā)布事件,getState---獲取狀態(tài)
其實(shí)他們做的事都很簡單:subscribe把接受方法(事件)push(入棧)進(jìn)一個(gè)數(shù)組,dispatch被調(diào)用時(shí)則依次執(zhí)行數(shù)組里的方法
/* 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'
};
//創(chuàng)建store樹
function createStore(reducer, initialState, enhancer) { //參數(shù)匹配
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對(duì)createStore進(jìn)行擴(kuò)展
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 = []; //存儲(chǔ)事件隊(duì)列
var nextListeners = currentListeners; //存儲(chǔ)備份事件隊(duì)列
var isDispatching = false;
//備份事件隊(duì)列---此方法存在的意義:防止在隊(duì)列中操作事件隊(duì)列(對(duì)事件隊(duì)列增刪)導(dǎo)致數(shù)據(jù)混亂
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);
//閉包緩存正在監(jiān)聽的事件,可以通過:var unsub=subscribe(listener); unsub()來卸載此事件
return function unsubscribe() {
if (!isSubscribed) {
return;
}
isSubscribed = false;
//備份事件隊(duì)列再進(jìn)行卸載操作
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
//發(fā)布事件
function dispatch(action) {
//檢測(cè)action是否是字面量對(duì)象
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;
//執(zhí)行reducer更新state
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
//同步事件隊(duì)列---執(zhí)行最新的事件隊(duì)列
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很簡單就此跳過,咱們進(jìn)入模塊4。模塊4也比較簡單主體:isPlainObject方法主要是檢測(cè)是否是字面量對(duì)象或者是直接實(shí)例化Object構(gòu)造函數(shù)的實(shí)例對(duì)象
/* 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直接構(gòu)造出來的實(shí)例
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);
}
//參數(shù)的構(gòu)造函數(shù)時(shí)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:此模塊的邏輯比較復(fù)雜,但是實(shí)現(xiàn)的東西卻很簡單:包裝了createStore方法與createStore里的dispatch方法,使dispath支持異步。 applyMiddleware參數(shù)是redux提供的兩個(gè)中間件:redux-thunks、redux-logger,兩個(gè)中間件提供方法對(duì)dispatch進(jìn)行包裝。
/* 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) {
//返回一個(gè)包裝的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
});
};
};
}
對(duì)dispatch進(jìn)行了怎樣的包裝呢???其實(shí)只是添加了一條判斷語句,這條判斷語句有什么作用?很簡單!如果是方法則執(zhí)行該方法,否則執(zhí)行dispath更新state。
為什么需要這樣做?因?yàn)楫?dāng)你在action存放一些不需要立即更新state的動(dòng)作(如異步請(qǐng)求),單純的action是無法滿足的(因?yàn)閐ispatch后就會(huì)馬上更新state),
所以需要對(duì)dispatch進(jìn)行包裝。包裝后怎么使用dispath呢?之前的功能一樣可以使用,需要用到異步的時(shí)候你可以返回一個(gè)方法,在這個(gè)方法里面執(zhí)行真正的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)執(zhí)行了這個(gè)方法
return function (next) {
//返回一個(gè)包裝的dispacth
return function (action) {
if (typeof action === 'function') {
return action(dispatch, getState);
}
return next(action); //由于閉包next一直存在于包裝的dispatch里,next其實(shí)是一個(gè)普通的dispatch,雖然經(jīng)過了createLogger方法(redux-logger里面內(nèi)置的一個(gè)方法)的包裝, 但是主要作用與createStore定義時(shí)的dispatch方法是一樣的
};
};
}
模塊6:把a(bǔ)ction與dispatch方法綁定在一起,即把每個(gè)action包裝著一個(gè)dispatch方法,然后執(zhí)行action時(shí)就會(huì)自動(dòng)dispath
/* 6 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = bindActionCreators; //包裝器---返回一個(gè)自動(dòng)執(zhí)行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);
}
//判斷是否是對(duì)象,不是對(duì)象則報(bào)錯(cuò)
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"?');
}
//獲取鍵名數(shù)組
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:執(zhí)行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并檢測(cè)時(shí)候會(huì)出錯(cuò)
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 = {};
//過濾參數(shù)---把reducers里的方法放進(jìn)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分發(fā)給每一個(gè)reducer,并執(zhí)行返回新的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];//獲取一個(gè)reducer方法
var previousStateForKey = state[key]; //獲取上次的state
var nextStateForKey = reducer(previousStateForKey, action);//執(zhí)行reducer
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;//判斷上次的state與現(xiàn)在的state是否相等
}
return hasChanged ? nextState : state;
};
}
模塊8:檢測(cè)ie9以下的宿主對(duì)象,即dom與bom,就不上源碼了
模塊9:檢測(cè)是否是對(duì)象
總結(jié)一下:
redux是不是很簡單?就那么幾個(gè)方法:createStore,subscribe,dispatch,getState,applyMiddleware,bindActionCreators,combineReducers。
createStore:創(chuàng)建store樹;
createStore->subscribe:訂閱事件,把監(jiān)聽的執(zhí)行的方法放進(jìn)來,其實(shí)就是一個(gè)數(shù)組;
createStore->dispatch:發(fā)布,執(zhí)行所有的監(jiān)聽事件,且執(zhí)行reducer更新state;
createStore->getState:獲取state;
applyMiddleware:包裝createStore與dispatch;
bindActionCreators:包裝所有的action方法,給每個(gè)action包裝一個(gè)dispatch方法,使執(zhí)行action方法就會(huì)自動(dòng)觸發(fā)dispatch方法
combineReducers:合并多個(gè)reducer;
總結(jié)
以上是生活随笔為你收集整理的react-redux源码解析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 石敢当是谁?
- 下一篇: React系列——react-redux