// 把 reducer,state,listener 都保存到闭包中,供下面的函数处理时使用 let currentReducer = reducer let currentState = preloadedState as S let currentListeners: (() =>void)[] | null = [] let nextListeners = currentListeners let isDispatching = false // 创建了若干函数用于操作数据流
// 获取当前的数据状态 functiongetState() {}
// 订阅 functionsubscribe() {}
// 派发事件 functiondispatch() {}
// 替换 reducer functionreplaceReducer() {}
// 监听 state 变化的观测器 // https://github.com/tc39/proposal-observable functionobservable() {}
// 发起初始化的 action,这个是内部的action,需要在业务代码中有对应的 reducer 才会触发响应 dispatch({ type: ActionTypes.INIT } as A)
const store = { dispatch: dispatch as Dispatch<A>, subscribe, getState, replaceReducer, [$$observable]: observable } as unknown as Store<ExtendState<S, StateExt>, A, StateExt, Ext> & Ext
// 最后返回了一个大对象,把上述创建的函数都丢了出去 return store; }
getState
1 2 3 4 5 6
// src/createStore.ts
// 获取当前的数据状态 functiongetState() { return currentState as S }
// This action has a similar effect to ActionTypes.INIT. // Any reducers that existed in both the new and old rootReducer // will receive the previous state. This effectively populates // the new state tree with any relevant data from the old one. 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 }