Redux 源码分析

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。

此文章为阅读 Redux 源码 作的笔记。

还有许多分析的不充分的地方,以后会慢慢补充。

index.js

这是Redux的入口文件,把模块都exprot出去

import createStore from './createStore';
import combineReducers from './combineReducers';
import bindActionCreators from './bindActionCreators';
import applyMiddleware from './applyMiddleware';
import compose from './compose';
import warning from './utils/warning';

/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}

if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
  warning('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
}

export { createStore, combineReducers, bindActionCreators, applyMiddleware, compose };
复制代码

creatStore.js

createStore 描述文档

store 描述文档

'use strict';

exports.__esModule = true;
exports.ActionTypes = undefined;
exports['default'] = createStore;

var _isPlainObject = require('lodash/isPlainObject');
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _symbolObservable = require('symbol-observable');
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var ActionTypes = exports.ActionTypes = {
  INIT: '@@redux/INIT'
  
};function createStore(reducer, preloadedState, enhancer) {
  var _ref2;
  
  //如果没有传第三个参数 则和第二个参数调换
  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState;
    preloadedState = undefined;
  }
  
  //判断enhancer如果不为undefined 则判断s是否function类型 不是则抛出错误
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.');
    }
    
    //返回 一个被enhancerz处理过的store create
    return enhancer(createStore)(reducer, preloadedState);
  }
  
  //判断reducer不为function类型 则抛出错误
  if (typeof reducer !== 'function') {
    throw new Error('Expected the reducer to be a function.');
  }

  //存储当前Reduer
  var currentReducer = reducer;
  //存储当前State
  var currentState = preloadedState;
  //存储当前处理事件数组
  var currentListeners = [];
  //存储下个处理事件数组
  var nextListeners = currentListeners;
  //是否调用dispatch中识标 赋值为false
  var isDispatching = false;

  
  function ensureCanMutateNextListeners() {
    //如果下个处理事件和当前处理事件引用相同,则下个处理事件为当前事件的复制
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice();
    }
  }

  //获取当前State
  function getState() {
    return currentState;
  }
  
  
  //订阅事件
  function subscribe(listener) {
    //订阅事件不为function 抛出错误
    if (typeof listener !== 'function') {
      throw new Error('Expected listener to be a function.');
    }
    
    //是否订阅中识标 赋值为true
    var isSubscribed = true;
    
    //判断下次处理事件和当前处理事件引用是否相同
    ensureCanMutateNextListeners();
    //把订阅事件加入下次处理事件数组
    nextListeners.push(listener);
    
    //返回取消订阅函数
    return function unsubscribe() {
      //如果不为订阅中 则在这里return
      if (!isSubscribed) {
        return;
      }
      //是否订阅中 赋值为false
      isSubscribed = false;
      
      //判断下次处理事件和当前处理事件引用是否相同
      ensureCanMutateNextListeners();
      
      //查找事件为在下次处理事件数组中的Index
      var index = nextListeners.indexOf(listener);
      //在下次处理事件中移除事件
      nextListeners.splice(index, 1);
    };
  }
  
  //dispatch触发函数
  function dispatch(action) {
    
    if (!(0, _isPlainObject2['default'])(action)) {
      throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
    }
    
    //action.type为undefined 抛出错误
    if (typeof action.type === 'undefined') {
      throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
    }
    
    //如果调用dispatch中 抛出错误
    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.');
    }

    try {
      //调用dispatch中识标 设置为true
      isDispatching = true;
      //生成新State 赋值给当前State
      currentState = currentReducer(currentState, action);
    } finally {
      //以上完 调用dispatch中识标 设置为false
      isDispatching = false;
    }
    
    声明事件数组 等于 当前事件数组currentListeners 等于 下次要执行的事件数组nextListeners 
    var listeners = currentListeners = nextListeners;
    //执行所有事件
    for (var i = 0; i < listeners.length; i++) {
      var listener = listeners[i];
      listener();
    }
    
    返回 参数action
    return action;
  }
  
  //替换Reduce
  function replaceReducer(nextReducer) {
    //参数nextReducer不为function类型 抛出错误
    if (typeof nextReducer !== 'function') {
      throw new Error('Expected the nextReducer to be a function.');
    }
    
    //当前Redcuer替换为nextReducer
    currentReducer = nextReducer;
    //初始化store
    dispatch({ type: ActionTypes.INIT });
  }
  
  function observable() {
    var _ref;

    var outerSubscribe = subscribe;
    return _ref = {
      subscribe: function subscribe(observer) {
        if (typeof observer !== 'object') {
          throw new TypeError('Expected the observer to be an object.');
        }

        function observeState() {
          if (observer.next) {
            observer.next(getState());
          }
        }

        observeState();
        var unsubscribe = outerSubscribe(observeState);
        return { unsubscribe: unsubscribe };
      }
    }, _ref[_symbolObservable2['default']] = function () {
      return this;
    }, _ref;
  }

  // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.
  
  //初始化store
  dispatch({ type: ActionTypes.INIT });

  return _ref2 = {
    dispatch: dispatch,
    subscribe: subscribe,
    getState: getState,
    replaceReducer: replaceReducer
  }, _ref2[_symbolObservable2['default']] = observable, _ref2;
}
复制代码

compose.js

compose 描述文档

"use strict";

exports.__esModule = true;
exports["default"] = compose;

function compose() {
  //遍历所有参数 存到funs的数组里面
  for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
    funcs[_key] = arguments[_key];
  }
  
  //如果funs长度为0 的返回
  if (funcs.length === 0) {
    return function (arg) {
      return arg;
    };
  }
  
  //如果funs长度为1 的返回
  if (funcs.length === 1) {
    return funcs[0];
  }
  
  //以上判断都不是 则到这里 递归funs里所有函数 返回递归后的值
  return funcs.reduce(function (a, b) {
    return function () {
      return a(b.apply(undefined, arguments));
    };
  });
}
复制代码

combineReducers.js

combineReducers 描述文档

import { ActionTypes } from './createStore';
import isPlainObject from 'lodash-es/isPlainObject';
import warning from './utils/warning';

function getUndefinedStateErrorMessage(key, action) {
  var actionType = action && action.type;
  var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';

  return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state. ' + 'If you want this reducer to hold no value, you can return null instead of undefined.';
}

function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
  var reducerKeys = Object.keys(reducers);
  var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';

  if (reducerKeys.length === 0) {
    return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
  }

  if (!isPlainObject(inputState)) {
    return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
  }

  var unexpectedKeys = Object.keys(inputState).filter(function (key) {
    return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
  });

  unexpectedKeys.forEach(function (key) {
    unexpectedKeyCache[key] = true;
  });

  if (unexpectedKeys.length > 0) {
    return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
  }
}

function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(function (key) {
    var reducer = reducers[key];
    var initialState = reducer(undefined, { type: ActionTypes.INIT });

    if (typeof initialState === 'undefined') {
      throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined. If you don\'t want to set a value for this reducer, ' + 'you can use null instead of undefined.');
    }

    var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
    if (typeof reducer(undefined, { type: type }) === 'undefined') {
      throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined, but can be null.');
    }
  });
}

export default function combineReducers(reducers) {
  //枚举出reducers的所有key
  var reducerKeys = Object.keys(reducers);
  var finalReducers = {};
  
  //遍历reducers对象
  for (var i = 0; i < reducerKeys.length; i++) {
    var key = reducerKeys[i];

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        warning('No reducer provided for key "' + key + '"');
      }
    }
    
    //如果成员为function 赋值给finalReducers
    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key];
    }
  }
  
  //枚举出finalReducerKeys的所有key
  var finalReducerKeys = Object.keys(finalReducers);
  
  //以下是各种 检查抛错
  var unexpectedKeyCache = void 0;
  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {};
  }

  var shapeAssertionError = void 0;
  try {
    assertReducerShape(finalReducers);
  } catch (e) {
    shapeAssertionError = e;
  }

  return function combination() {
    //如果参数数量大于0与第一个参数为undefined,则state为第一个参数不然为空对象 
    var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    //action为第二个参数
    var action = arguments[1];
    
    // 如果shapeAssertionError 不为undefined (说明捕获到错误,这个错误是检查到有不标准的reducer) 则抛出错误
    if (shapeAssertionError) {
      throw shapeAssertionError;
    }
    
    //如果不是生产环境,会有一些警告
    if (process.env.NODE_ENV !== 'production') {
      var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
      if (warningMessage) {
        warning(warningMessage);
      }
    }
   
    var hasChanged = false;
    var nextState = {};
    //遍历finalReducerKeys
    for (var _i = 0; _i < finalReducerKeys.length; _i++) {
      //_key 等于 遍历到的成员的Key
      var _key = finalReducerKeys[_i];
      //reducer 等于 遍历到的成员的值
      var reducer = finalReducers[_key];
      var previousStateForKey = state[_key];
      //调用renduer
      var nextStateForKey = reducer(previousStateForKey, action);
      //如果renduer返回的state是undefined 则抛出错误
      if (typeof nextStateForKey === 'undefined') {
        var errorMessage = getUndefinedStateErrorMessage(_key, action);
        throw new Error(errorMessage);
      }
      //新state不为undefined 赋值给nextState对象
      nextState[_key] = nextStateForKey;
      //如果有一个新state如果和旧state不相等 //hasChanged就会变会true,之后都hasChange都会为true说明state已经改变
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    }
    
    // nextState就是 遍历完renduce处理后的新state合成一个新state树
    //判断hasChanged 为true就返回nextState 否则返回旧state
    return hasChanged ? nextState : state;
  };
}
复制代码

bindActionCreators.js

bindActionCreators 描述文档

//绑定新的actionCreator和dispatch 函数 
function bindActionCreator(actionCreator, dispatch) {
  return function () {
    return dispatch(actionCreator.apply(undefined, arguments));
  };
}

export default function bindActionCreators(actionCreators, dispatch) {
  
  //如果第一个参数actionCreators为function类型  
  //把actionCreators,dispatch传入bindActionCreator函数并返回
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch);
  }
    
  //如果第actionCreators不是object类型 或者是null 则抛出错误
  if (typeof actionCreators !== 'object' || actionCreators === null) {
    throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
  }
  
  // 枚举出actionCreators所有的key
  var keys = Object.keys(actionCreators);
  var boundActionCreators = {};
  
  //为bindActionCreator每个成员 注入actionCreator和dispatch
  //然后赋值给boundActionCreators对象
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var actionCreator = actionCreators[key];
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
    }
  }
  
  返回 boundActionCreators
  return boundActionCreators;
}
复制代码

applyMiddleware.js

applyMiddleware 描述文档

//判断支不支持Object.assign 否则自己实现一个
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

import compose from './compose';

export default function applyMiddleware() {
  //遍历所有参数 存到middlewares数组中
  for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
    middlewares[_key] = arguments[_key];
  }

  //返回 可传入createStore的方法
  return function (createStore) {
    //返回一个createStore
    return function (reducer, preloadedState, enhancer) {
      //创建store
      var store = createStore(reducer, preloadedState, enhancer);
      //store.dispatch 赋值给 dispatch变量 
      var _dispatch = store.dispatch;
      //链式调用方法数组
      var chain = [];
      
      //middlewareAPI getState还是那个getState,调用dispatch会调用下面的_dispatch
      var middlewareAPI = {
        getState: store.getState,
        dispatch: function dispatch(action) {
          return _dispatch(action);
        }
      };
      //map middlewares返回调用middlewareAPI后的值
      chain = middlewares.map(function (middleware) {
        return middleware(middlewareAPI);
      });
      
      //可见上面compose源码,用于合成多个函数 
      //链式调用chain 调用后的值再传入store.dispatch调用
      _dispatch = compose.apply(undefined, chain)(store.dispatch);
        
      //合并对象 并返回
      return _extends({}, store, {
        dispatch: _dispatch
      });
    };
  };
}复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值