Skip to content

Instantly share code, notes, and snippets.

@Gyumeijie
Last active March 9, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gyumeijie/920780bf22b58d8094bc0460d7417a0d to your computer and use it in GitHub Desktop.
Save Gyumeijie/920780bf22b58d8094bc0460d7417a0d to your computer and use it in GitHub Desktop.
some beautiful design
1. 中间件接口
{dispatch, getState} => next => action => your code
中间件串联在一起时,在需要的时候通过调用next来调用下一个中间件,因此需要建立各个中间件next参数之间的连接(类似数据结构中链表节点中next);
compose(...chain)(store.dispatch)语句相当于从后建立起了各个中间件next参数之间的连接关系,其中最后一个中间件的next的值为store.dispatch
使用compose函数合成多个函数的时候,内层函数的返回值称为外层函数的参数,外层函数可以通过这个参数引用内层函数的的返回值
中间件1 中间件2 中间件3 中间件4
第一层 next next next next
--- --- --- --- *
第二层 ** action next-> action next-> action next -> action next->end_next
--- --- --- ---
{inner code} {inner code} {inner code} {inner code}
A. 在第一层通过向合成的函数传入一个next的值, 建立next之间的连接个,合成函数内的各个函数执行方向是右到左;
B. 在第二层通过向中间件1传入action值,内部的代码开始执行,由于javascript支持闭包,所以在inner code可以通过
调用next(action)调用下一个中间件,依次类推,此时执行方向是从左到右;
C. 外层的next的作用就是为了起连接作用的;
D. compose(...chain)(store.dispatch)是合成的dispatch函数,实际上是中间件1的返回函数,该函数带一个action的参数。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment