Redux百行程式碼千行文件
接觸Redux不過短短半年,從開始看官方文件的一頭霧水,到漸漸已經理解了Redux到底是在做什麼,但是絕大數場景下Redux都是配合React一同使用的,因而會引入了React-Redux庫,但是正是因為React-Redux庫封裝了大量方法,使得我們對Redux的理解變的開始模糊。這篇文章將會在Redux原始碼的角度分析Redux,希望你在閱讀之前有部分Redux的基礎。
上圖是Redux的流程圖,具體的不做介紹,不瞭解的同學可以查閱一下Redux的官方文件。寫的非常詳細。下面的程式碼結構為Redux的master分支:
├── 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,這個部分程式碼已經不需要再次解釋了,沒有看過的同學戳這裡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。無論是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有更深的理解。