redux中applyMiddleware源码,中文注释

栏目: 服务器 · 发布时间: 7年前

内容简介:理解applyMiddleware需要跟createStore结合.首先来看createStore是怎样创建store的.再来看createStore 的源码

理解applyMiddleware需要跟createStore结合.首先来看createStore是怎样创建store的.

redux中applyMiddleware源码,中文注释

再来看createStore 的源码

redux中applyMiddleware源码,中文注释

createStore的第三个参数enhancer就是applyMiddleware,此时createStore会返回enhancer(createStore)(reducer, preloadedState),也就是createStore在中间件里面去执行了

applyMiddleware返回的是函数A(也就是applyMiddleware(...middlewares) =函数A,然后又跑到createStore里面作为第三个参数),所以能把createStore作为参数传进去

redux中applyMiddleware源码,中文注释

一个小例子,测试返回函数后是什么东西

redux中applyMiddleware源码,中文注释

import compose from './compose'

/**
 * Creates a store enhancer that applies middleware to the dispatch method
 * of the Redux store. This is handy for a variety of tasks, such as expressing
 * asynchronous actions in a concise manner, or logging every action payload.
 *
 * 创建一个redux store的dispatch方法使用中间件的store增强器.  对于不同的人任务,这将会
 * 非常方便,比如可以用非常简单的方式进行异步操作,或者输出action的payload
 * 
 * See `redux-thunk` package as an example of the Redux middleware.
 *查看`redux-thunk`包作为一个redux中间件的例子
 *
 * Because middleware is potentially asynchronous, this should be the first
 * store enhancer in the composition chain.
 *
 * 因为中间件默认是异步的,这应该是合成链中的第一个store增强器
 * 
 * Note that each middleware will be given the `dispatch` and `getState` functions
 * as named arguments.
 *注意每个中间件都会以`dispatch` and `getState`方法作为参数
 * @param {...Function} middlewares The middleware chain to be applied.提供的中间件
 * @returns {Function} A store enhancer applying the middleware.store增强器应用的中间件
 */
export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preloadedState, enhancer) => {
    const store = createStore(reducer, preloadedState, enhancer)
    let dispatch = store.dispatch
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (action) => dispatch(action)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

史玉柱自述

史玉柱自述

优米网 / 同心出版社 / 2013-6-1 / 42.00元

史玉柱迄今为止唯一公开著作。 亲口讲述24年创业历程与营销心得。 中国商业思想史里程碑之作! 24年跌宕起伏,功成身退,史玉柱向您娓娓道来,历经时间沉淀的商业智慧和人生感悟。 在书中,史玉柱毫无保留地回顾了创业以来的经历和各阶段的思考。全书没有深奥的理论,铅华洗尽、朴实无华,往往在轻描淡写之间,一语道破营销的本质。 关于产品开发、营销传播、广告投放、团队管理、创业投资......一起来看看 《史玉柱自述》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试