redux createStore 源码学习
2017-09-18 本文已影响16人
strong9527
createStore在redux类库中是篇幅最长的一个函数。它主要的作用是构建redux的store。
当createStore函数遇到enhance参数
function createStore(reducer, 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)
}
在createStore函数中,只要enhancer存在,创建store的过程将会在enhancer函数中完成。这保证了可以在enhancer函数中装饰和包装dispatch核心方法。有兴趣可看:applyMiddleware源码分析
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.')
}
//这就是为什么reducer函数处理返回数据出现错误也不报错的原因。
//直接在dispatch函数内进行错误处理,reducer处理action的错误并不会报给开发者。
//(真坑爹,这导致开发者很难进行错误追踪。)
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
}
初始化store的state
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT })
源代码中的英文注释,已经说明了这一行代码的作用。