接觸Redux不過短短半年,從開始看官方文檔的一頭霧水,到漸漸已經了解了Redux到底是在做什麼,但是絕大數場景下Redux都是配合React一同使用的,因而會引入了React-Redux庫,但是正是因為React-Redux庫封裝了大量方法,使得我們對Redux的了解變的開始模糊。這篇文章将會在Redux源碼的角度分析Redux,希望你在閱讀之前有部分Redux的基礎。

├── applyMiddleware.js
├── bindActionCreators.js
├── combineReducers.js
├── compose.js
├── createStore.js
├── index.js
└── utils
└── warning.js
Redux中src檔案夾下目錄如上所示,檔案名基本就是對應我們所熟悉的Redux的API,首先看一下index.js中的代碼:
/*
* 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)指代的是沒有函數體的函數),然後判斷執行時的函數名是否和預定義的一樣,就像上面的代碼:
function isCrushed() {}
if(typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed'){
//has minified
}
compose
從易到難,我們在看一個稍微簡單的對外方法compose
/**
* 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:
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.
reduce()函數對一個累加值和數組中的每一個元素(從左到右)應用一個函數,将其reduce成一個單值,例如:
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,這個部分代碼已經不需要再次解釋了,沒有看過的同學戳這裡,裡面有詳細的介紹。
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。無論是dispatchaction時,還是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處理了哪幾種問題:
1.reducer中是不是存在reducer
2.state是否是純Object對象
3.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有更深的了解。