# Redux 源码解析

# createStore(reducer, preloadedState?, enhancer?)

function createStore(reducer, preloadedState, enhancer) {
  // 省略...
  if (enhancer) {
    enhancer(createStore)(reducer, preloadedState);
  }
  // 初始化
  dispatch({ type: ActionTypes.INIT });
  // 省略...
  return {
    dispatch,
    getState,
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# applyMiddleware

function applyMiddleware(...middlewares) {
  return (createStore) => {
    // 创建store
    const store = createStore();

    const middlewareAPI: MiddlewareAPI = {
      getState: store.getState,
      dispatch: (action, ...args) => dispatch(action, ...args),
    };
    const chain = middlewares.map((middleware) => middleware(middlewareAPI));
    // compose 方法很巧妙
    dispatch = compose<typeof dispatch>(...chain)(store.dispatch);

    return {
      ...store,
      dispatch,
    };
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 中间件代码格式

中间件是一个函数,默认会传入 getState 和 dispatch 两个参数供中间件使用

# thunk

// 核心代码
function thunkMiddleware({ getState, dispatch }) {
  return (next) => (action) => next(action);
}
1
2
3
4

# createLogger

// 核心代码
function createLogger({ getState }) {
  return (next) => (action) => {
    // TODO 处理中间件逻辑
  };
}
1
2
3
4
5
6