接觸Redux不太短短半年,從開始看官方文檔的一頭霧水,到漸漸已經理解了Redux究竟是在作什麼,可是絕大數場景下Redux都是配合React一同使用的,於是會引入了React-Redux庫,可是正是由於React-Redux庫封裝了大量方法,使得咱們對Redux的理解變的開始模糊。這篇文章將會在Redux源碼的角度分析Redux,但願你在閱讀以前有部分Redux的基礎。javascript
上圖是Redux的流程圖,具體的不作介紹,不瞭解的同窗能夠查閱一下Redux的官方文檔。寫的很是詳細。下面的代碼結構爲Redux的master分支:前端
├── applyMiddleware.js
├── bindActionCreators.js
├── combineReducers.js
├── compose.js
├── createStore.js
├── index.js
└── utilsjava
└── warning.js
Redux中src文件夾下目錄如上所示,文件名基本就是對應咱們所熟悉的Redux的API,首先看一下index.js中的代碼:webpack
/* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if ( process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed' ) { warning( 'You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.' ) } export { createStore, combineReducers, bindActionCreators, applyMiddleware, compose }
上面的代碼很是的簡單了,只不過是把全部的方法對外導出。其中isCrushed
是用來檢查函數名是否已經被壓縮(minification)。若是函數當前不是在生產環境中而且函數名被壓縮了,就提示用戶。process是Node 應用自帶的一個全局變量,能夠獲取當前進程的若干信息。在許多前端庫中,常常會使用 process.env.NODE_ENV這個環境變量來判斷當前是在開發環境仍是生產環境中。這個小例子咱們能夠get到一個hack的方法,若是判斷一個js函數名時候被壓縮呢?咱們能夠先預約義一個虛函數(雖然JavaScript中沒有虛函數一說,這裏的虛函數(dummy function)指代的是沒有函數體的函數),而後判斷執行時的函數名是否和預約義的同樣,就像上面的代碼:git
function isCrushed() {} if(typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed'){ //has minified }
compose
從易到難,咱們在看一個稍微簡單的對外方法compose
github
/** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ export default function compose(...funcs) { if (funcs.length === 0) { return arg => arg } if (funcs.length === 1) { return funcs[0] } return funcs.reduce((a, b) => (...args) => a(b(...args))) }
理解這個函數以前咱們首先看一下reduce
方法,這個方法我是看了好多遍如今仍然是印象模糊,雖然以前介紹過reduce
,可是仍是再次回憶一下Array.prototye.reduce
:web
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.redux
reduce()
函數對一個累加值和數組中的每個元素(從左到右)應用一個函數,將其reduce
成一個單值,例如:segmentfault
var sum = [0, 1, 2, 3].reduce(function(acc, val) { return acc + val; }, 0); // sum is 6
reduce()
函數接受兩個參數:一個回調函數和初始值,回調函數會被從左到右應用到數組的每個元素,其中回調函數的定義是數組
/** * accumulator: 累加器累加回調的值,它是上一次調用回調時返回的累積值或者是初始值 * currentValue: 當前數組遍歷的值 * currenIndex: 當前元素的索引值 * array: 整個數組 */ function (accumulator,currentValue,currentIndex,array){ }
如今回頭看看compose
函數都在作什麼,compose
函數從左到右組合(compose)多個單參函數。最右邊的函數能夠按照定義接受多個參數,若是compose
的參數爲空,則返回一個空函數。若是參數長度爲1,則返回函數自己。若是函數的參數爲數組,這時候咱們返回
return funcs.reduce((a, b) => (...args) => a(b(...args)))
咱們知道reduce
函數返回是一個值。上面函數傳入的回調函數是(a, b) => (...args) => a(b(...args))
其中a
是當前的累積值,b
是數組中當前遍歷的值。假設調用函數的方式是compose(f,g,h)
,首先第一次執行回調函數時,a
的實參是函數f
,b
的實參是g
,第二次調用的是,a
的實參是(...args) => f(g(...args))
,b
的實參是h
,最後函數返回的是(...args) =>x(h(...args))
,其中x爲(...args) => f(g(...args))
,因此咱們最後能夠推導出運行compose(f,g,h)
的結果是(...args) => f(g(h(...args)))
。發現了沒有,這裏其實經過reduce
實現了reduceRight
的從右到左遍歷的功能,可是卻使得代碼相對較難理解。在Redux 1.0.1版本中compose
的實現以下:
export default function compose(...funcs) { return funcs.reduceRight((composed, f) => f(composed)); }
這樣看起來是否是更容易理解compose
函數的功能。
bindActionCreators
bindActionCreators
也是Redux中很是常見的API,主要實現的就是將ActionCreator
與dispatch
進行綁定,看一下官方的解釋:
Turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly.
翻譯過來就是bindActionCreators
將值爲actionCreator
的對象轉化成具備相同鍵值的對象,可是每個actionCreator
都會被dispatch
所包裹調用,所以能夠直接使用。話很少說,來看看它是怎麼實現的:
import warning from './utils/warning' function bindActionCreator(actionCreator, dispatch) { return (...args) => dispatch(actionCreator(...args)) } export default 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"?` ) } const keys = Object.keys(actionCreators) const boundActionCreators = {} for (let i = 0; i < keys.length; i++) { const key = keys[i] const actionCreator = actionCreators[key] if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } else { warning(`bindActionCreators expected a function actionCreator for key '${key}', instead received type '${typeof actionCreator}'.`) } } return boundActionCreators }
對於處理單個actionCreator
的方法是
function bindActionCreator(actionCreator, dispatch) { return (...args) => dispatch(actionCreator(...args)) }
代碼也是很是的簡單,無非是返回一個新的函數,該函數調用時會將actionCreator
返回的純對象進行dispatch
。而對於函數bindActionCreators
首先會判斷actionCreators
是否是函數,若是是函數就直接調用bindActionCreator
。當actionCreators
不是對象時會拋出錯誤。接下來:
const keys = Object.keys(actionCreators) const boundActionCreators = {} for (let i = 0; i < keys.length; i++) { const key = keys[i] const actionCreator = actionCreators[key] if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } else { warning(`bindActionCreators expected a function actionCreator for key '${key}', instead received type '${typeof actionCreator}'.`) } } return boundActionCreators
這段代碼也是很是簡單,甚至我以爲我都能寫出來,無非就是對對象actionCreators
中的全部值調用bindActionCreator
,而後返回新的對象。恭喜你,又解鎖了一個文件~
applyMiddleware
applyMiddleware
是Redux Middleware的一個重要API,這個部分代碼已經不須要再次解釋了,沒有看過的同窗戳這裏Redux:Middleware你咋就這麼難,裏面有詳細的介紹。
createStore
createStore
做爲Redux的核心API,其做用就是生成一個應用惟一的store。其函數的簽名爲:
function createStore(reducer, preloadedState, enhancer) {}
前兩個參數很是熟悉,reducer
是處理的reducer
純函數,preloadedState
是初始狀態,而enhancer
使用相對較少,enhancer
是一個高階函數,用來對原始的createStore
的功能進行加強。具體咱們能夠看一下源碼:
具體代碼以下:
import isPlainObject from 'lodash/isPlainObject' import $$observable from 'symbol-observable' export const ActionTypes = { INIT: '@@redux/INIT' } export default function createStore(reducer, preloadedState, enhancer) { if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState preloadedState = undefined } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.') } return enhancer(createStore)(reducer, preloadedState) } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.') } let currentReducer = reducer let currentState = preloadedState let currentListeners = [] let nextListeners = currentListeners let isDispatching = false function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice() } } function getState() { return currentState } function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.') } let isSubscribed = true ensureCanMutateNextListeners() nextListeners.push(listener) return function unsubscribe() { if (!isSubscribed) { return } isSubscribed = false ensureCanMutateNextListeners() const index = nextListeners.indexOf(listener) nextListeners.splice(index, 1) } } function dispatch(action) { if (!isPlainObject(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) } finally { isDispatching = false } const listeners = currentListeners = nextListeners for (let i = 0; i < listeners.length; i++) { const listener = listeners[i] listener() } return action } function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.') } currentReducer = nextReducer dispatch({ type: ActionTypes.INIT }) } function observable() { const outerSubscribe = subscribe return { subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.') } function observeState() { if (observer.next) { observer.next(getState()) } } observeState() const unsubscribe = outerSubscribe(observeState) return { unsubscribe } }, [$$observable]() { return this } } } dispatch({ type: ActionTypes.INIT }) return { dispatch, subscribe, getState, replaceReducer, [$$observable]: observable } }
咱們來逐步解讀一下:
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState preloadedState = undefined }
咱們發現若是沒有傳入參數enhancer
,而且preloadedState
的值又是一個函數的話,createStore
會認爲你省略了preloadedState
,所以第二個參數就是enhancer
。
if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.') } return enhancer(createStore)(reducer, preloadedState) } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.') }
若是你傳入了enhancer
可是卻又不是函數類型。會拋出錯誤。若是傳入的reducer
也不是函數,拋出相關錯誤。接下來纔是createStore
重點,初始化:
let currentReducer = reducer let currentState = preloadedState let currentListeners = [] let nextListeners = currentListeners let isDispatching = false
currentReducer
是用來存儲當前的reducer
函數。currentState
用來存儲當前store中的數據,初始化爲默認的preloadedState
,currentListeners
用來存儲當前的監聽者。而isDispatching
用來當前是否屬於正在處理dispatch
的階段。而後函數聲明瞭一系列函數,最後返回了:
{ dispatch, subscribe, getState, replaceReducer, [$$observable]: observable }
顯然能夠看出來返回來的函數就是store
。好比咱們能夠調用store.dispatch
。讓咱們依次看看各個函數在作什麼。
dispatch
function dispatch(action) { if (!isPlainObject(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) } finally { isDispatching = false } const listeners = currentListeners = nextListeners for (let i = 0; i < listeners.length; i++) { const listener = listeners[i] listener() } return action }
咱們看看dispath
作了什麼,首先檢查傳入的action
是否是純對象,若是不是則拋出異常。而後檢測,action
中是否存在type
,不存在也給出相應的錯誤提示。而後判斷isDispatching
是否爲true
,主要是預防的是在reducer
中作dispatch
操做,若是在reduder
中作了dispatch
,而dispatch
又必然會致使reducer
的調用,就會形成死循環。而後咱們將isDispatching
置爲true
,調用當前的reducer
函數,而且返回新的state
存入currentState
,並將isDispatching
置回去。最後依次調用監聽者store
已經發生了變化,可是咱們並無將新的store
做爲參數傳遞給監聽者,由於咱們知道監聽者函數內部能夠經過調用惟一獲取store
的函數store.getState()
獲取最新的store
。
getState
function getState() { return currentState }
實在太簡單了,自行體會。
replaceReducer
function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.') } currentReducer = nextReducer dispatch({ type: ActionTypes.INIT }) }
replaceReducer
的使用相對也是很是少的,主要用戶熱更新reducer
。
subscribe
function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.') } let isSubscribed = true ensureCanMutateNextListeners() nextListeners.push(listener) return function unsubscribe() { if (!isSubscribed) { return } isSubscribed = false ensureCanMutateNextListeners() const index = nextListeners.indexOf(listener) nextListeners.splice(index, 1) } }
subscribe
用來訂閱store
變化的函數。首先判斷傳入的listener
是不是函數。而後又調用了ensureCanMutateNextListeners
,
function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice() } }
能夠看到ensureCanMutateNextListeners
用來判斷nextListeners
和currentListeners
是不是徹底相同,若是相同(===
),將nextListeners
賦值爲currentListeners
的拷貝(值相同,但不是同一個數組),而後將當前的監聽函數傳入nextListeners
。最後返回一個unsubscribe
函數用來移除當前監聽者函數。須要注意的是,isSubscribed
是以閉包的形式判斷當前監聽者函數是否在監聽,從而保證只有第一次調用unsubscribe
纔是有效的。可是爲何會存在nextListeners
呢?
首先能夠在任什麼時候間點添加listener
。不管是dispatch
action時,仍是state
值正在發生改變的時候。可是須要注意的,在每一次調用dispatch
以前,訂閱者僅僅只是一份快照(snapshot),若是是在listeners
被調用期間發生訂閱(subscribe)或者解除訂閱(unsubscribe),在本次通知中並不會當即生效,而是在下次中生效。所以添加的過程是在nextListeners
中添加的訂閱者,而不是直接添加到currentListeners
。而後在每一次調用dispatch
的時候都會作:
const listeners = currentListeners = nextListeners
來同步currentListeners
和nextListeners
。
### observable
該部分不屬於本次文章講解到的內容,主要涉及到RxJS和響應異步Action。之後有機會(主要是我本身搞明白了),會單獨講解。
## combineReducers
combineReducers
的主要做用就是將大的reducer
函數拆分紅一個個小的reducer
分別處理,看一下它是如何實現的:
export default function combineReducers(reducers) { const reducerKeys = Object.keys(reducers) const finalReducers = {} for (let i = 0; i < reducerKeys.length; i++) { const key = reducerKeys[i] if (process.env.NODE_ENV !== 'production') { if (typeof reducers[key] === 'undefined') { warning(`No reducer provided for key "${key}"`) } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key] } } const finalReducerKeys = Object.keys(finalReducers) let unexpectedKeyCache if (process.env.NODE_ENV !== 'production') { unexpectedKeyCache = {} } let shapeAssertionError try { assertReducerShape(finalReducers) } catch (e) { shapeAssertionError = e } return function combination(state = {}, action) { if (shapeAssertionError) { throw shapeAssertionError } if (process.env.NODE_ENV !== 'production') { const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache) if (warningMessage) { warning(warningMessage) } } let hasChanged = false const nextState = {} for (let i = 0; i < finalReducerKeys.length; i++) { const key = finalReducerKeys[i] const reducer = finalReducers[key] const previousStateForKey = state[key] const nextStateForKey = reducer(previousStateForKey, action) if (typeof nextStateForKey === 'undefined') { const errorMessage = getUndefinedStateErrorMessage(key, action) throw new Error(errorMessage) } nextState[key] = nextStateForKey hasChanged = hasChanged || nextStateForKey !== previousStateForKey } return hasChanged ? nextState : state } }
首先,經過一個for
循環去遍歷參數reducers
,將對應值爲函數的屬性賦值到finalReducers
。而後聲明變量unexpectedKeyCache
,若是在非生產環境,會將其初始化爲{}
。而後執行assertReducerShape(finalReducers)
,若是拋出異常會將錯誤信息存儲在shapeAssertionError
。咱們看一下shapeAssertionError
在作什麼?
function assertReducerShape(reducers) { Object.keys(reducers).forEach(key => { const reducer = reducers[key] const initialState = reducer(undefined, { type: 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. If you don't want to set a value for this reducer, ` + `you can use null instead of undefined.` ) } const type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.') if (typeof reducer(undefined, { type }) === 'undefined') { throw new Error( `Reducer "${key}" returned undefined when probed with a random type. ` + `Don't try to handle ${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, but can be null.` ) } }) }
能夠看出assertReducerShape
函數的主要做用就是判斷reducers
中的每個reducer
在action
爲{ type: ActionTypes.INIT }
時是否有初始值,若是沒有則會拋出異常。而且會對reduer
執行一次隨機的action
,若是沒有返回,則拋出錯誤,告知你不要處理redux中的私有的action,對於未知的action應當返回當前的stat。而且初始值不能爲undefined
可是能夠是null
。
接着咱們看到combineReducers
返回了一個combineReducers
函數:
return function combination(state = {}, action) { if (shapeAssertionError) { throw shapeAssertionError } if (process.env.NODE_ENV !== 'production') { const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache) if (warningMessage) { warning(warningMessage) } } let hasChanged = false const nextState = {} for (let i = 0; i < finalReducerKeys.length; i++) { const key = finalReducerKeys[i] const reducer = finalReducers[key] const previousStateForKey = state[key] const nextStateForKey = reducer(previousStateForKey, action) if (typeof nextStateForKey === 'undefined') { const errorMessage = getUndefinedStateErrorMessage(key, action) throw new Error(errorMessage) } nextState[key] = nextStateForKey hasChanged = hasChanged || nextStateForKey !== previousStateForKey } return hasChanged ? nextState : state }
在combination
函數中咱們首先對shapeAssertionError
中可能存在的異常進行處理。接着,若是是在開發環境下,會執行getUnexpectedStateShapeWarningMessage
,看看getUnexpectedStateShapeWarningMessage
是如何定義的:
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { const reducerKeys = Object.keys(reducers) const argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState 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 (!isPlainObject(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('", "')}"` ) } const unexpectedKeys = Object.keys(inputState).filter(key => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key] ) unexpectedKeys.forEach(key => { unexpectedKeyCache[key] = true }) 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.` ) } }
咱們簡要地看看getUnexpectedStateShapeWarningMessage
處理了哪幾種問題:
reducer中是否是存在reducer
state是不是純Object對象
state中存在reducer沒有處理的項,可是僅會在第一次提醒,以後就忽略了。
而後combination
執行其核心部分代碼:
let hasChanged = false const nextState = {} for (let i = 0; i < finalReducerKeys.length; i++) { const key = finalReducerKeys[i] const reducer = finalReducers[key] const previousStateForKey = state[key] const nextStateForKey = reducer(previousStateForKey, action) if (typeof nextStateForKey === 'undefined') { const errorMessage = getUndefinedStateErrorMessage(key, action) throw new Error(errorMessage) } nextState[key] = nextStateForKey hasChanged = hasChanged || nextStateForKey !== previousStateForKey } return hasChanged ? nextState : state
使用變量nextState
記錄本次執行reducer
返回的state。hasChanged
用來記錄先後state
是否發生改變。循環遍歷reducers
,將對應的store
的部分交給相關的reducer
處理,固然對應各個reducer
返回的新的state
仍然不能夠是undefined
。最後根據hasChanged
是否改變來決定返回nextState
仍是state
,這樣就保證了在不變的狀況下仍然返回的是同一個對象。
最後,其實咱們發現Redux的源碼很是的精煉,也並不複雜,可是Dan Abramov能從Flux的思想演變到如今的Redux思想也是很是不易,但願此篇文章使得你對Redux有更深的理解。