Redux中间件组合方法
中间件
https://redux.js.org/glossary#middleware
中间件在发送端 action端点 和 处理方reducer的端点之间。
主要负责将async action转换为action, 或者记录action日志。
A middleware is a higher-order function that composes a dispatch function to return a new dispatch function. It often turns async actions into actions.
Middleware is composable using function composition. It is useful for logging actions, performing side effects like routing, or turning an asynchronous API call into a series of synchronous actions.
import { createStore, applyMiddleware } from 'redux'
import todos from './reducers' function logger({ getState }) {
return next => action => {
console.log('will dispatch', action) // Call the next dispatch method in the middleware chain.
const returnValue = next(action) console.log('state after dispatch', getState()) // This will likely be the action itself, unless
// a middleware further in chain changed it.
return returnValue
}
} const store = createStore(todos, ['Use Redux'], applyMiddleware(logger)) store.dispatch({
type: 'ADD_TODO',
text: 'Understand the middleware'
})
// (These lines will be logged by the middleware:)
// will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }
// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
let next = store.dispatch;
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action);
next(action);
console.log('next state', store.getState());
}
上面代码中,对
store.dispatch
进行了重定义,在发送 Action 前后添加了打印功能。这就是中间件的雏形。中间件就是一个函数,对
store.dispatch
方法进行了改造,在发出 Action 和执行 Reducer 这两步之间,添加了其他功能。
应用多个中间件
https://redux.js.org/api/applymiddleware
applyMiddleware(...middleware)
Middleware is the suggested way to extend Redux with custom functionality. Middleware lets you wrap the store's
dispatch
method for fun and profit. The key feature of middleware is that it is composable. Multiple middleware can be combined together, where each middleware requires no knowledge of what comes before or after it in the chain.Arguments
...middleware
(arguments): Functions that conform to the Redux middleware API. Each middleware receivesStore
'sdispatch
andgetState
functions as named arguments, and returns a function. That function will be given thenext
middleware's dispatch method, and is expected to return a function ofaction
callingnext(action)
with a potentially different argument, or at a different time, or maybe not calling it at all. The last middleware in the chain will receive the real store'sdispatch
method as thenext
parameter, thus ending the chain. So, the middleware signature is({ getState, dispatch }) => next => action
.Returns
(Function) A store enhancer that applies the given middleware. The store enhancer signature is
createStore => createStore
but the easiest way to apply it is to pass it tocreateStore()
as the lastenhancer
argument.
应用中间件函数实现, 注意其中 对于middlewares数组, 使用compose函数进行组合, 其串联方式是从 右 到 左, 即最右边的被包裹为最里层,最先执行, 最左边的被包裹到最外面, 最后执行。
https://www.cnblogs.com/liaozhenting/p/10166671.html
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
`Dispatching while constructing your middleware is not allowed. ` +
`Other middleware would not be applied to this dispatch.`
)
} const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch) return {
...store,
dispatch
}
}
}
如下图很形象:
https://zhuanlan.zhihu.com/p/20597452
compose
https://www.cnblogs.com/liaozhenting/p/10166671.html
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/ export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
} if (funcs.length === 1) {
return funcs[0]
} return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
与pipe正好相反:
const pipe = (...fns) => {
return (args) => {
return fns.reduce((args, fn) => {
return fn(args)
}, args)
}
} const toUpper = (value) => {
return value.toUpperCase();
} const addFont = (value) => {
return 'hello plus!' + value;
} console.log(pipe(addFont,toUpper)('test'));
// HELLO PLUS!TEST
跟pip函数对比
console.log(pipe(addFont,toUpper)('test'));
// HELLO PLUS!TEST
console.log(compose(addFont,toUpper)('test'));
// hello plus!TEST
underscore compose
http://www.bootcss.com/p/underscore/#compose
compose
_.compose(*functions)
返回函数集 functions 组合后的复合函数,
也就是一个函数执行完之后把返回的结果再作为参数赋给下一个函数来执行.
以此类推.
在数学里, 把函数 f(), g(), 和 h() 组合起来可以得到复合函数 f(g(h()))。var greet = function(name){ return "hi: " + name; };
var exclaim = function(statement){ return statement.toUpperCase() + "!"; };
var welcome = _.compose(greet, exclaim);
welcome('moe');
=> 'hi: MOE!'
Redux中间件组合方法的更多相关文章
- react+redux教程(七)自定义redux中间件
今天,我们要讲解的是自定义redux中间件这个知识点.本节内容非常抽象,特别是中间件的定义原理,那多层的函数嵌套和串联,需要极强逻辑思维能力才能完全消化吸收.不过我会多罗嗦几句,所以不用担心. 例子 ...
- 【React全家桶入门之十三】Redux中间件与异步action
在上一篇中我们了解到,更新Redux中状态的流程是这种:action -> reducer -> new state. 文中也讲到.action是一个普通的javascript对象.red ...
- redux中间件和redux-thunk实现原理
redux-thunk这个中间件可以使我们把这样的异步请求或者说复杂的逻辑可以放到action里面去处理,redux-thunk使redux的一个中间件,为什么叫做中间件 我们说中间件,那么肯定是谁和 ...
- Redux 中间件与函数式编程
为什么需要中间件 接触过 Express 的同学对"中间件"这个名词应该并不陌生.在 Express 中,中间件就是一些用于定制对特定请求的处理过程的函数.作为中间件的函数是相互独 ...
- 3.3 理解 Redux 中间件(转)
这一小节会讲解 redux 中间件的原理,为下一节讲解 redux 异步 action 做铺垫,主要内容为: Redux 中间件是什么 使用 Redux 中间件 logger 中间件结构分析 appl ...
- 理解 Redux 中间件机制
Redux 的 action 是一个 JS 对象,它表明了如何对 store 进行修改.但是 Redux 的中间件机制使action creator 不光可以返回 action 对象,也可以返回 ac ...
- Redux:中间件
redux中间件概念 比较容易理解. 在使用redux时,改变store state的一个固定套路是调用store.dispatch(action)方法,将action送到reducer中. 所谓中间 ...
- react第十八单元(redux中间件redux-thunk,redux工程目录的样板代码,规范目录结构)
第十八单元(redux中间件redux-thunk,redux工程目录的样板代码,规范目录结构) #课程目标 中间件:中间件增强redux的可扩展性,实现功能复用的目的. redux-thunk异步逻 ...
- redux 中间件 redux-saga 使用教程
redux 中间件 redux-saga 使用教程 redux middleware refs https://redux-saga.js.org/docs/ExternalResources.htm ...
随机推荐
- Redmine入门-安装
Redmine提供了两种方式安装,如果仅仅只是使用Redmine,建议采用一键安装的方式,快捷方便.如果需要做二次开发或者更多的个性化处理,可以采用源码安装方式,下面分别介绍两种安装方式. ----- ...
- 内存与IO的交换【转】
用户进程的内存页分为两种: file-backed pages(文件背景页) anonymous pages(匿名页) 比如进程的代码段.映射的文件都是file-backed,而进程的堆.栈都是不与文 ...
- Win7系统下,docker构建nginx+php7环境实践
前面两章介绍的是Windows系统下如何安装和配置docker,主要原因在于,公司大多人数用的是Windows环境,想通过在Windows环境上,通过docker,构建一个公用的配置. 首先要说明的是 ...
- RocketMQ4.3.x 史上配置最全详解,没有之一
最近整理了RocketMQ的配置参数一部分参考rocketmq技术内幕,一部分自己看源码猜测,有表述不清楚或不正确请广大网友指正 这里应该是最全的配置解析了,搞了2天.以后查询就好办了,仅此贡献给广大 ...
- #034Python选修课第二届Turtle绘图大赛
Pythonturtle库选修课作业 目录 目录 代码效果 题目要求 合作同学 程序实现 最初目标 实现方式 代码如下 代码效果 题目要求 具体内容可参阅课程教学网站或超星学习通. 按照2人一组,结对 ...
- git 多用户多仓库配置
ssh全称是Secure Shell,即安全Shell,是一种可以进行安全远程登录的协议,在Linux中以OpenSSH为代表,Windows中则有Putty作为实现.ssh的会话建立阶段类似TCP协 ...
- dede织梦 arclist标签完美支持currentstyle属性
由于客户需求,所以进行对文章的arclist标签进行设置当前样式(currentstyle),修改前记得备份. dede版本v5.7sp 找到PHP修改: include/taglib/arclist ...
- 禁止Cnario Player启动后自动开始播放
Cnario Player安装激活后, 默认开机后自动启动, 启动加载内容完成后进入10秒倒计时, 10秒后即开始播放关机前播放的内容. 如果不想让其自动开始播放, 可按照如下办法设置其不自动播放. ...
- ExcelPower_Helper插件功能简述与演示
部分功能演示简述: 1.文件目录浏览功能 此功能主要利用了ribbon的dynamicmenu控件,动态呈现自定义目录下的文件列表信息,支持点击打开,查看文件所在目录.功能来源于大神li ...
- Python中的 sort 和 sorted
今天在做一道题时,因为忘了Python中sort和sorted的用法与区别导致程序一直报错,找了好久才知道是使用方法错误的问题!现在就大致的归纳一下sort和sorted的用法与区别 1. sort: ...