redux 源码整理分析学习
- redux/src/index.js
/*** 导出redux文件*/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'import __DO_NOT_USE__ActionTypes from './utils/actionTypes'/** 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 setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' +'to ensure you have the correct code for your production build.')}export {createStore,combineReducers,bindActionCreators,applyMiddleware,compose,__DO_NOT_USE__ActionTypes}
- createStore.js文件
import $$observable from 'symbol-observable'// 定义初始化的actionimport ActionTypes from './utils/actionTypes'import isPlainObject from './utils/isPlainObject'/*** Creates a Redux store that holds the state tree.* The only way to change the data in the store is to call `dispatch()` on it.** There should only be a single store in your app. To specify how different* parts of the state tree respond to actions, you may combine several reducers* into a single reducer function by using `combineReducers`.** @param {Function} reducer A function that returns the next state tree, given* the current state tree and the action to handle.** @param {any} [preloadedState] The initial state. You may optionally specify it* to hydrate the state from the server in universal apps, or to restore a* previously serialized user session.* If you use `combineReducers` to produce the root reducer function, this must be* an object with the same shape as `combineReducers` keys.** @param {Function} [enhancer] The store enhancer. You may optionally specify it* to enhance the store with third-party capabilities such as middleware,* time travel, persistence, etc. The only store enhancer that ships with Redux* is `applyMiddleware()`.** @returns {Store} A Redux store that lets you read the state, dispatch actions* and subscribe to changes.@param {Function} reducer : 这个函数接收state和action,作一系列计算之后返回一个新的state。这里就体现了函数式编程的一些特性:第一,这个reducer是一个纯函数,纯函数的特点是:对于相同的输入,永远会得到相同的输出,而且没有任何可观察的副作用,也不依赖外部环境的状态。不理解纯函数的筒子们,可以上网搜索一下。第二,state是不可变的,我们这里对state作的一些修改和计算,不是直接修改原来的数据,而是返回修改之后的数据,原来的数据是保持不变。这里可以衍生到immutable,可以使用immutable和redux搭配使用。2、@param {any} [preloadedState]这是初始化的state3、@param {Function} [enhancer]这个enhancer其实就是一个中间件,它在redux3.1.0之后才加入的。相当于把store做一些增强处理,让store更强大,功能更丰富,在之后的applyMiddleware那里会详细说的。这里也体现了高阶函数的思想,就像react-redux的connect方法一样,做一些包装处理之后,再返回。4、@returns {Store}这是返回的值,返回的是一棵状态树,也就是store啦。*/// createStore返回的最常用的三个api是dispatch,subscribe,getState,一般我们只要传入// reducer和preloadedState, 就可以直接调用这三个方法,非常方便。export default function createStore(reducer, preloadedState, enhancer) {// 1. preloadedState , enhancer都为function则报错if ((typeof preloadedState === 'function' && typeof enhancer === 'function') ||(typeof enhancer === 'function' && typeof arguments[3] === 'function')) {throw new Error('It looks like you are passing several store enhancers to ' +'createStore(). This is not supported. Instead, compose them ' +'together to a single function.')}// 要保证enhance为function, 如果preloaderState为function,enhancer为undefined,// 则交换 enhancer = preloadedStateif (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {enhancer = preloadedStatepreloadedState = undefined}// 如果传入了第三个参数,但不是一个函数,就报错if (typeof enhancer !== 'undefined') {if (typeof enhancer !== 'function') {throw new Error('Expected the enhancer to be a function.')}//这是一个高阶函数调用方法。这里的enhancer就是applyMiddleware(...middlewares)//enhancer接受createStore作为参数,对createStore的能力进行增强,并返回增强后的createStore//然后再将reducer和preloadedState作为参数传给增强后的createStore,得到最终生成的store// 对自己进行功能的增强return enhancer(createStore)(reducer, preloadedState)}//reducer不是函数,报错if (typeof reducer !== 'function') {throw new Error('Expected the reducer to be a function.')}// 定义变量let currentReducer = reducer // 赋值为reducerlet currentState = preloadedState // 赋值preloadedStatelet currentListeners = [] // 当前的监听器列表let nextListeners = currentListeners //更新后的监听器列表let isDispatching = false //是否正在dispatch/*** This makes a shallow copy of currentListeners so we can use* nextListeners as a temporary list while dispatching.** This prevents any bugs around consumers calling* subscribe/unsubscribe in the middle of a dispatch.*/// 判断当前listener和更新后的listener是不是同一个引用,如果是的话对当前listener进行一个拷贝,防止在操作新的listener列表的时候对正在发生的业务逻辑造成影响function ensureCanMutateNextListeners() {if (nextListeners === currentListeners) {nextListeners = currentListeners.slice()}}/*** Reads the state tree managed by the store.** @returns {any} The current state tree of your application.*/// 获取当前的state,如果正在发起isDispatching, 不能直接调用state;// 返回当前的state列表function getState() {if (isDispatching) {throw new Error('You may not call store.getState() while the reducer is executing. ' +'The reducer has already received the state as an argument. ' +'Pass it down from the top reducer instead of reading it from the store.')}return currentState}/*** Adds a change listener. It will be called any time an action is dispatched,* and some part of the state tree may potentially have changed. You may then* call `getState()` to read the current state tree inside the callback.** You may call `dispatch()` from a change listener, with the following* caveats:** 1. The subscriptions are snapshotted just before every `dispatch()` call.* If you subscribe or unsubscribe while the listeners are being invoked, this* will not have any effect on the `dispatch()` that is currently in progress.* However, the next `dispatch()` call, whether nested or not, will use a more* recent snapshot of the subscription list.** 2. The listener should not expect to see all state changes, as the state* might have been updated multiple times during a nested `dispatch()` before* the listener is called. It is, however, guaranteed that all subscribers* registered before the `dispatch()` started will be called with the latest* state by the time it exits.** @param {Function} listener A callback to be invoked on every dispatch.* @returns {Function} A function to remove this change listener.*/// 这个函数是给store添加监听函数// listener: 每一个dispatch的后都会执行listener, 传入listener// 注册监听这个函数之后,subscribe方法会返回一个unsubscribe()方法,来注销刚才添加的监听函数function subscribe(listener) {// 为参数添加验证if (typeof listener !== 'function') {throw new Error('Expected the listener to be a function.')}if (isDispatching) {throw new Error('You may not call store.subscribe() while the reducer is executing. ' +'If you would like to be notified after the store has been updated, subscribe from a ' +'component and invoke store.getState() in the callback to access the latest state. ' +'See https://redux.js.org/api-reference/store#subscribelistener for more details.')}let isSubscribed = trueensureCanMutateNextListeners()nextListeners.push(listener)return function unsubscribe() {if (!isSubscribed) {return}if (isDispatching) {throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' +'See https://redux.js.org/api-reference/store#subscribelistener for more details.')}isSubscribed = falseensureCanMutateNextListeners()const index = nextListeners.indexOf(listener)nextListeners.splice(index, 1)currentListeners = null}}/*** Dispatches an action. It is the only way to trigger a state change.** The `reducer` function, used to create the store, will be called with the* current state tree and the given `action`. Its return value will* be considered the **next** state of the tree, and the change listeners* will be notified.** The base implementation only supports plain object actions. If you want to* dispatch a Promise, an Observable, a thunk, or something else, you need to* wrap your store creating function into the corresponding middleware. For* example, see the documentation for the `redux-thunk` package. Even the* middleware will eventually dispatch plain object actions using this method.** @param {Object} action A plain object representing “what changed”. It is* a good idea to keep actions serializable so you can record and replay user* sessions, or use the time travelling `redux-devtools`. An action must have* a `type` property which may not be `undefined`. It is a good idea to use* string constants for action types.** @returns {Object} For convenience, the same action object you dispatched.** Note that, if you use a custom middleware, it may wrap `dispatch()` to* return something else (for example, a Promise you can await).*/function dispatch(action) {if (!isPlainObject(action)) {throw new Error('Actions must be plain objects. ' +'Use custom middleware for async actions.')}if (typeof action.type === 'undefined') {throw new Error('Actions may not have an undefined "type" property. ' +'Have you misspelled a constant?')}if (isDispatching) {throw new Error('Reducers may not dispatch actions.')}try {isDispatching = truecurrentState = currentReducer(currentState, action)} finally {isDispatching = false}const listeners = (currentListeners = nextListeners)for (let i = 0; i < listeners.length; i++) {const listener = listeners[i]listener()}return action}/*** Replaces the reducer currently used by the store to calculate the state.** You might need this if your app implements code splitting and you want to* load some of the reducers dynamically. You might also need this if you* implement a hot reloading mechanism for Redux.** @param {Function} nextReducer The reducer for the store to use instead.* @returns {void}*/function replaceReducer(nextReducer) {if (typeof nextReducer !== 'function') {throw new Error('Expected the nextReducer to be a function.')}currentReducer = nextReducer// This action has a similiar 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 })}/*** Interoperability point for observable/reactive libraries.* @returns {observable} A minimal observable of state changes.* For more information, see the observable proposal:* https://github.com/tc39/proposal-observable*/function observable() {const outerSubscribe = subscribereturn {/*** The minimal observable subscription method.* @param {Object} observer Any object that can be used as an observer.* The observer object should have a `next` method.* @returns {subscription} An object with an `unsubscribe` method that can* be used to unsubscribe the observable from the store, and prevent further* emission of values from the observable.*/subscribe(observer) {if (typeof observer !== 'object' || observer === null) {throw new TypeError('Expected the observer to be an object.')}function observeState() {if (observer.next) {observer.next(getState())}}observeState()const unsubscribe = outerSubscribe(observeState)return { unsubscribe }},[$$observable]() {return this}}}// 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.dispatch({ type: ActionTypes.INIT })return {dispatch,subscribe,getState,replaceReducer,[$$observable]: observable}}
