redux-promise-mutex
配合redux-thunk使用,可以自动对一些异步的action加锁。
使用场景
- 触发了一个异步的action,处理时间比较长,如果这个时候用户继续操作会不断触发新的action。如果不希望重复请求通常需要我们手动加锁处理,而使用了redux-promise-mutex后只需要按照一定规则书写action即可自动加锁。
如何使用
/* Store */;;; // promiseMutex 位置必须在 redux-thunk 之前const middlewares = promiseMutex thunkMiddleware; const store = ; /* Actions */ { // actions 必须返回函数(与redux-thunk相同),且该函数不能为匿名函数 return { //函数必须返回一个Promise/类Promise对象 return { ; }; }} /* Pages */;
具体要求
0、中间件顺序必须在redux-thunk之前 1、action 返回一个函数。(这个也是 redux-thunk 异步操作的要求) 2、action 返回的函数必须是 * 非匿名函数 * ,或者函数带有 uuid 属性 3、函数返回值为 Promise / 类Promise 对象(可以进行then操作)
为何要使用?
可以过滤掉短时间内重复的action。
/* without redux-promise-mutex */forlet i = 0; i < 10; i++ ;// => 2秒后有10个console /* with redux-promise-mutex */forlet i = 0; i < 10; i++ ;// => 2秒后只有1个console