接触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
└── utils
└── warning.jsjava
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
的主要做用就是将大的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
处理了哪几种问题:
而后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有更深的理解。