export type State = Readonly>; export type Action = { type: string; payload: any; }; export type Reducer = (s: S, a: A) => S; type Listener = (ns: S, ps?: S) => void; type Unsubscribe = () => void; export interface Store { dispatch: (a: A) => void; getState: () => S; subscribe: (listener: Listener) => Unsubscribe; } /** * 简单实现的 Redux * @param preloadedState 初始 state * @param reducer reducer pure function * @returns store */ function createStore(preloadedState: S, reducer: Reducer): Store, A> { const listeners: Listener[] = []; let currentState = preloadedState; const dispatch = (action: A) => { const nextState = reducer(currentState, action); const prevState = currentState; currentState = nextState; for (const cb of listeners) { cb(currentState, prevState); } }; const subscribe = (listener: Listener) => { let isSubscribed = true; listeners.push(listener); return () => { if (!isSubscribed) { return; } const index = listeners.indexOf(listener); listeners.splice(index, 1); isSubscribed = false; }; }; const getState = () => { return currentState; }; return { dispatch, getState, subscribe, }; } export default createStore;