redux 源码整理分析学习

    1. redux/src/index.js
    1. /**
    2. * 导出redux文件
    3. */
    4. import createStore from './createStore'
    5. import combineReducers from './combineReducers'
    6. import bindActionCreators from './bindActionCreators'
    7. import applyMiddleware from './applyMiddleware'
    8. import compose from './compose'
    9. import warning from './utils/warning'
    10. import __DO_NOT_USE__ActionTypes from './utils/actionTypes'
    11. /*
    12. * This is a dummy function to check if the function name has been altered by minification.
    13. * If the function has been minified and NODE_ENV !== 'production', warn the user.
    14. */
    15. function isCrushed() {}
    16. if (
    17. process.env.NODE_ENV !== 'production' &&
    18. typeof isCrushed.name === 'string' &&
    19. isCrushed.name !== 'isCrushed'
    20. ) {
    21. warning(
    22. 'You are currently using minified code outside of NODE_ENV === "production". ' +
    23. 'This means that you are running a slower development build of Redux. ' +
    24. 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
    25. 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' +
    26. 'to ensure you have the correct code for your production build.'
    27. )
    28. }
    29. export {
    30. createStore,
    31. combineReducers,
    32. bindActionCreators,
    33. applyMiddleware,
    34. compose,
    35. __DO_NOT_USE__ActionTypes
    36. }
    1. createStore.js文件
    1. import $$observable from 'symbol-observable'
    2. // 定义初始化的action
    3. import ActionTypes from './utils/actionTypes'
    4. import isPlainObject from './utils/isPlainObject'
    5. /**
    6. * Creates a Redux store that holds the state tree.
    7. * The only way to change the data in the store is to call `dispatch()` on it.
    8. *
    9. * There should only be a single store in your app. To specify how different
    10. * parts of the state tree respond to actions, you may combine several reducers
    11. * into a single reducer function by using `combineReducers`.
    12. *
    13. * @param {Function} reducer A function that returns the next state tree, given
    14. * the current state tree and the action to handle.
    15. *
    16. * @param {any} [preloadedState] The initial state. You may optionally specify it
    17. * to hydrate the state from the server in universal apps, or to restore a
    18. * previously serialized user session.
    19. * If you use `combineReducers` to produce the root reducer function, this must be
    20. * an object with the same shape as `combineReducers` keys.
    21. *
    22. * @param {Function} [enhancer] The store enhancer. You may optionally specify it
    23. * to enhance the store with third-party capabilities such as middleware,
    24. * time travel, persistence, etc. The only store enhancer that ships with Redux
    25. * is `applyMiddleware()`.
    26. *
    27. * @returns {Store} A Redux store that lets you read the state, dispatch actions
    28. * and subscribe to changes.
    29. @param {Function} reducer : 这个函数接收state和action,作一系列计算之后返回一个新的state。
    30. 这里就体现了函数式编程的一些特性:
    31. 第一,这个reducer是一个纯函数,纯函数的特点是:对于相同的输入,永远会得到相同的输出,而且没有
    32. 任何可观察的副作用,也不依赖外部环境的状态。不理解纯函数的筒子们,可以上网搜索一下。
    33. 第二,state是不可变的,我们这里对state作的一些修改和计算,不是直接修改原来的数据,而是返回修改
    34. 之后的数据,原来的数据是保持不变。这里可以衍生到immutable,可以使用immutable和redux搭配使用。
    35. 2、@param {any} [preloadedState]
    36. 这是初始化的state
    37. 3、@param {Function} [enhancer]
    38. 这个enhancer其实就是一个中间件,它在redux3.1.0之后才加入的。相当于把store做一些增强处理,
    39. 让store更强大,功能更丰富,在之后的applyMiddleware那里会详细说的。这里也体现了高阶函数的思想,
    40. 就像react-redux的connect方法一样,做一些包装处理之后,再返回。
    41. 4、@returns {Store}
    42. 这是返回的值,返回的是一棵状态树,也就是store啦。
    43. */
    44. // createStore返回的最常用的三个api是dispatch,subscribe,getState,一般我们只要传入
    45. // reducer和preloadedState, 就可以直接调用这三个方法,非常方便。
    46. export default function createStore(reducer, preloadedState, enhancer) {
    47. // 1. preloadedState , enhancer都为function则报错
    48. if (
    49. (typeof preloadedState === 'function' && typeof enhancer === 'function') ||
    50. (typeof enhancer === 'function' && typeof arguments[3] === 'function')
    51. ) {
    52. throw new Error(
    53. 'It looks like you are passing several store enhancers to ' +
    54. 'createStore(). This is not supported. Instead, compose them ' +
    55. 'together to a single function.'
    56. )
    57. }
    58. // 要保证enhance为function, 如果preloaderState为function,enhancer为undefined,
    59. // 则交换 enhancer = preloadedState
    60. if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    61. enhancer = preloadedState
    62. preloadedState = undefined
    63. }
    64. // 如果传入了第三个参数,但不是一个函数,就报错
    65. if (typeof enhancer !== 'undefined') {
    66. if (typeof enhancer !== 'function') {
    67. throw new Error('Expected the enhancer to be a function.')
    68. }
    69. //这是一个高阶函数调用方法。这里的enhancer就是applyMiddleware(...middlewares)
    70. //enhancer接受createStore作为参数,对createStore的能力进行增强,并返回增强后的createStore
    71. //然后再将reducer和preloadedState作为参数传给增强后的createStore,得到最终生成的store
    72. // 对自己进行功能的增强
    73. return enhancer(createStore)(reducer, preloadedState)
    74. }
    75. //reducer不是函数,报错
    76. if (typeof reducer !== 'function') {
    77. throw new Error('Expected the reducer to be a function.')
    78. }
    79. // 定义变量
    80. let currentReducer = reducer // 赋值为reducer
    81. let currentState = preloadedState // 赋值preloadedState
    82. let currentListeners = [] // 当前的监听器列表
    83. let nextListeners = currentListeners //更新后的监听器列表
    84. let isDispatching = false //是否正在dispatch
    85. /**
    86. * This makes a shallow copy of currentListeners so we can use
    87. * nextListeners as a temporary list while dispatching.
    88. *
    89. * This prevents any bugs around consumers calling
    90. * subscribe/unsubscribe in the middle of a dispatch.
    91. */
    92. // 判断当前listener和更新后的listener是不是同一个引用,如果是的话对当前listener进行一个拷贝,
    93. 防止在操作新的listener列表的时候对正在发生的业务逻辑造成影响
    94. function ensureCanMutateNextListeners() {
    95. if (nextListeners === currentListeners) {
    96. nextListeners = currentListeners.slice()
    97. }
    98. }
    99. /**
    100. * Reads the state tree managed by the store.
    101. *
    102. * @returns {any} The current state tree of your application.
    103. */
    104. // 获取当前的state,如果正在发起isDispatching, 不能直接调用state;
    105. // 返回当前的state列表
    106. function getState() {
    107. if (isDispatching) {
    108. throw new Error(
    109. 'You may not call store.getState() while the reducer is executing. ' +
    110. 'The reducer has already received the state as an argument. ' +
    111. 'Pass it down from the top reducer instead of reading it from the store.'
    112. )
    113. }
    114. return currentState
    115. }
    116. /**
    117. * Adds a change listener. It will be called any time an action is dispatched,
    118. * and some part of the state tree may potentially have changed. You may then
    119. * call `getState()` to read the current state tree inside the callback.
    120. *
    121. * You may call `dispatch()` from a change listener, with the following
    122. * caveats:
    123. *
    124. * 1. The subscriptions are snapshotted just before every `dispatch()` call.
    125. * If you subscribe or unsubscribe while the listeners are being invoked, this
    126. * will not have any effect on the `dispatch()` that is currently in progress.
    127. * However, the next `dispatch()` call, whether nested or not, will use a more
    128. * recent snapshot of the subscription list.
    129. *
    130. * 2. The listener should not expect to see all state changes, as the state
    131. * might have been updated multiple times during a nested `dispatch()` before
    132. * the listener is called. It is, however, guaranteed that all subscribers
    133. * registered before the `dispatch()` started will be called with the latest
    134. * state by the time it exits.
    135. *
    136. * @param {Function} listener A callback to be invoked on every dispatch.
    137. * @returns {Function} A function to remove this change listener.
    138. */
    139. // 这个函数是给store添加监听函数
    140. // listener: 每一个dispatch的后都会执行listener, 传入listener
    141. // 注册监听这个函数之后,subscribe方法会返回一个unsubscribe()方法,来注销刚才添加的监听函数
    142. function subscribe(listener) {
    143. // 为参数添加验证
    144. if (typeof listener !== 'function') {
    145. throw new Error('Expected the listener to be a function.')
    146. }
    147. if (isDispatching) {
    148. throw new Error(
    149. 'You may not call store.subscribe() while the reducer is executing. ' +
    150. 'If you would like to be notified after the store has been updated, subscribe from a ' +
    151. 'component and invoke store.getState() in the callback to access the latest state. ' +
    152. 'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
    153. )
    154. }
    155. let isSubscribed = true
    156. ensureCanMutateNextListeners()
    157. nextListeners.push(listener)
    158. return function unsubscribe() {
    159. if (!isSubscribed) {
    160. return
    161. }
    162. if (isDispatching) {
    163. throw new Error(
    164. 'You may not unsubscribe from a store listener while the reducer is executing. ' +
    165. 'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
    166. )
    167. }
    168. isSubscribed = false
    169. ensureCanMutateNextListeners()
    170. const index = nextListeners.indexOf(listener)
    171. nextListeners.splice(index, 1)
    172. currentListeners = null
    173. }
    174. }
    175. /**
    176. * Dispatches an action. It is the only way to trigger a state change.
    177. *
    178. * The `reducer` function, used to create the store, will be called with the
    179. * current state tree and the given `action`. Its return value will
    180. * be considered the **next** state of the tree, and the change listeners
    181. * will be notified.
    182. *
    183. * The base implementation only supports plain object actions. If you want to
    184. * dispatch a Promise, an Observable, a thunk, or something else, you need to
    185. * wrap your store creating function into the corresponding middleware. For
    186. * example, see the documentation for the `redux-thunk` package. Even the
    187. * middleware will eventually dispatch plain object actions using this method.
    188. *
    189. * @param {Object} action A plain object representing “what changed”. It is
    190. * a good idea to keep actions serializable so you can record and replay user
    191. * sessions, or use the time travelling `redux-devtools`. An action must have
    192. * a `type` property which may not be `undefined`. It is a good idea to use
    193. * string constants for action types.
    194. *
    195. * @returns {Object} For convenience, the same action object you dispatched.
    196. *
    197. * Note that, if you use a custom middleware, it may wrap `dispatch()` to
    198. * return something else (for example, a Promise you can await).
    199. */
    200. function dispatch(action) {
    201. if (!isPlainObject(action)) {
    202. throw new Error(
    203. 'Actions must be plain objects. ' +
    204. 'Use custom middleware for async actions.'
    205. )
    206. }
    207. if (typeof action.type === 'undefined') {
    208. throw new Error(
    209. 'Actions may not have an undefined "type" property. ' +
    210. 'Have you misspelled a constant?'
    211. )
    212. }
    213. if (isDispatching) {
    214. throw new Error('Reducers may not dispatch actions.')
    215. }
    216. try {
    217. isDispatching = true
    218. currentState = currentReducer(currentState, action)
    219. } finally {
    220. isDispatching = false
    221. }
    222. const listeners = (currentListeners = nextListeners)
    223. for (let i = 0; i < listeners.length; i++) {
    224. const listener = listeners[i]
    225. listener()
    226. }
    227. return action
    228. }
    229. /**
    230. * Replaces the reducer currently used by the store to calculate the state.
    231. *
    232. * You might need this if your app implements code splitting and you want to
    233. * load some of the reducers dynamically. You might also need this if you
    234. * implement a hot reloading mechanism for Redux.
    235. *
    236. * @param {Function} nextReducer The reducer for the store to use instead.
    237. * @returns {void}
    238. */
    239. function replaceReducer(nextReducer) {
    240. if (typeof nextReducer !== 'function') {
    241. throw new Error('Expected the nextReducer to be a function.')
    242. }
    243. currentReducer = nextReducer
    244. // This action has a similiar effect to ActionTypes.INIT.
    245. // Any reducers that existed in both the new and old rootReducer
    246. // will receive the previous state. This effectively populates
    247. // the new state tree with any relevant data from the old one.
    248. dispatch({ type: ActionTypes.REPLACE })
    249. }
    250. /**
    251. * Interoperability point for observable/reactive libraries.
    252. * @returns {observable} A minimal observable of state changes.
    253. * For more information, see the observable proposal:
    254. * https://github.com/tc39/proposal-observable
    255. */
    256. function observable() {
    257. const outerSubscribe = subscribe
    258. return {
    259. /**
    260. * The minimal observable subscription method.
    261. * @param {Object} observer Any object that can be used as an observer.
    262. * The observer object should have a `next` method.
    263. * @returns {subscription} An object with an `unsubscribe` method that can
    264. * be used to unsubscribe the observable from the store, and prevent further
    265. * emission of values from the observable.
    266. */
    267. subscribe(observer) {
    268. if (typeof observer !== 'object' || observer === null) {
    269. throw new TypeError('Expected the observer to be an object.')
    270. }
    271. function observeState() {
    272. if (observer.next) {
    273. observer.next(getState())
    274. }
    275. }
    276. observeState()
    277. const unsubscribe = outerSubscribe(observeState)
    278. return { unsubscribe }
    279. },
    280. [$$observable]() {
    281. return this
    282. }
    283. }
    284. }
    285. // When a store is created, an "INIT" action is dispatched so that every
    286. // reducer returns their initial state. This effectively populates
    287. // the initial state tree.
    288. dispatch({ type: ActionTypes.INIT })
    289. return {
    290. dispatch,
    291. subscribe,
    292. getState,
    293. replaceReducer,
    294. [$$observable]: observable
    295. }
    296. }