subscribe(listener)
添加一個變化監(jiān)聽器骚秦,每當 dispatch action 的時候就會執(zhí)行她倘。
該方法主要有如下操作:
1璧微、將listener推入listeners隊列,等待dispatch action時調(diào)用硬梁。
2前硫、修改isSubscribe的值。
3荧止、返回unsubscribe函數(shù)屹电。(函數(shù)內(nèi)操作:1、修改isSubscribe值罩息;1嗤详、listeners隊列刪除listener)
代碼如下:
function subscribe(listener: () => void) {
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.')
}
if (isDispatching) {
throw new Error(
'You may not call store.subscribe() while the reducer is executing. ' +
'If you would like to be notified after the store has been updated, subscribe from a ' +
'component and invoke store.getState() in the callback to access the latest state. ' +
'See https://redux.js.org/api/store#subscribelistener for more details.'
)
}
let isSubscribed = true
ensureCanMutateNextListeners()
nextListeners.push(listener)
return function unsubscribe() {
if (!isSubscribed) {
return
}
if (isDispatching) {
throw new Error(
'You may not unsubscribe from a store listener while the reducer is executing. ' +
'See https://redux.js.org/api/store#subscribelistener for more details.'
)
}
isSubscribed = false
ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
currentListeners = null
}
}
replateReducer(nextReducer)
這個方法沒怎么用到過,代碼寫法也有地方?jīng)]看懂瓷炮。。递宅。
主要操作:
1娘香、將當前reducer替換為nextReducer。
2办龄、dispatch一個replace action烘绽。(dispatch的操作就是上面那個函數(shù)里的,修改屬性狀態(tài)啦俐填,執(zhí)行所有l(wèi)istener啦安接,返回action啦)
3、返回store英融。
代碼如下:
function replaceReducer<NewState, NewActions extends A>(
nextReducer: Reducer<NewState, NewActions>
): Store<ExtendState<NewState, StateExt>, NewActions, StateExt, Ext> & Ext {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.')
}
;((currentReducer as unknown) as Reducer<
NewState,
NewActions
>) = nextReducer
dispatch({ type: ActionTypes.REPLACE } as A)
// change the type of the store by casting it to the new store
return (store as unknown) as Store<
ExtendState<NewState, StateExt>,
NewActions,
StateExt,
Ext
> &
Ext
}
createStore文件的主要內(nèi)容就是這些盏檐,還有其他一些類型檢測以及工具函數(shù)的代碼未放上來,這個源碼里都有驶悟。