创建Store
大多数还是报错。我们不用关心报错。
if (
(typeof preloadedState === 'function' && typeof enhancer === 'function') ||
(typeof enhancer === 'function' && typeof arguments[3] === 'function')
) {
throw new Error(
'It looks like you are passing several store enhancers to ' +
'createStore(). This is not supported. Instead, compose them ' +
'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.'
)
}
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState as StoreEnhancer<Ext, StateExt>
preloadedState = undefined
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error(
`Expected the enhancer to be a function. Instead, received: '${kindOf(
enhancer
)}'`
)
}
return enhancer(createStore)(
reducer,
preloadedState as PreloadedState<S>
) as Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext
}
if (typeof reducer !== 'function') {
throw new Error(
`Expected the root reducer to be a function. Instead, received: '${kindOf(
reducer
)}'`
)
}
let currentReducer = reducer
let currentState = preloadedState as S
let currentListeners: (() => void)[] | null = []
let nextListeners = currentListeners
let isDispatching = false
1,如果有e,而且是函数。调用它。
调用e,参数是当前方法。返回值是个函数,继续调用它。 e相当于是一个createStore。 会跳过后续步骤。
return enhancer(createStore)(
reducer,
preloadedState as PreloadedState<S>
) as Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext
2,状态预热。
reducer,初始状态,订阅者数组。
let currentReducer = reducer
let currentState = preloadedState as S
let currentListeners: (() => void)[] | null = []
3,next赋值current。
let nextListeners = currentListeners
4,关闭标记。
let isDispatching = false
阶段总结
1,双缓冲机制
每次current复制一份给next。
next:负责修改。 添加和移除,都是操作它。
current:负责查询。 查询时,next赋值给current,然后遍历current。
2,标记管理
isDispatching:是否正在操作中。 每次dispatch时,打开它。 操作完毕,关闭它。 其他操作时,只要true就报错。
isSubscribed:订阅状态。 如果true,表示还没取消。 只有true时才进行取消操作。
|