What's connector

在解答 connector 是什么之前,我们来先看一个代码片段

  1. let hasChanged = false;
  2. const nextState = {};
  3. for (let i = 0; i < finalReducerKeys.length; i++) {
  4. const key = finalReducerKeys[i];
  5. const reducer = finalReducers[key];
  6. const previousStateForKey = state[key];
  7. const nextStateForKey = reducer(previousStateForKey, action);
  8. if (typeof nextStateForKey === 'undefined') {
  9. const errorMessage = getUndefinedStateErrorMessage(key, action);
  10. throw new Error(errorMessage);
  11. }
  12. nextState[key] = nextStateForKey;
  13. hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
  14. }
  15. return hasChanged ? nextState : state;

以上来自于 Reduxjs-combineReducers的核心实现。

combineReducers 是一个将 Reducer 分治的函数,让一个庞大数据的 Reducer 可以由多层的更小的 Reducer 组合而成。

这是 Redux 框架里的核心 API,但是他有缺点。他有非常明显的语言的局限性,如下 3 点:

  • 浅拷贝一个任意对象
  1. const nextState = {};
  • 读取字段
  1. const previousStateForKey = state[key];
  • 写入字段
  1. nextState[key] = nextStateForKey;

将上面的 3 点抽象来看:

  • State 的 clone 的能力(浅拷贝)
  • Get & Set 的能力,即为 Connector 的概念。有了 以上两点,我们才完全集成了 Redux 的所有精华,同时将它的设计更上一个通用的维度。