前言
众所周知,redux只单纯的提供数据流的管理,action也只接受plain object类型,那么如果我们需要在action中写异步就需要借助其他中间件;
学习的时候简陋的实现了一下redux-thunk、redux-promise、redux-logger, 特此记录(记笔记行为,仅供学习参考)。
redux-thunk
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | 
 
 
 
 function thunk({ getState, dispatch }) {
 return (next) => (action) => {
 if (typeof action === 'function') {
 return action(dispatch, getState)
 }
 return next(action)
 }
 }
 
 
 | 
redux-promise
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | import isPromise from 'is-promise'
 
 
 
 
 function promise({ getState, dispatch }) {
 return (next) => (action) => {
 isPromise(action) ? action.then(dispatch) : next(action)
 }
 }
 
 
 | 
redux-logger
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | 
 
 
 
 
 function logger({ getState, dispatch }) {
 return (next) => (action) => {
 console.group('reducer')
 const prevState = getState()
 
 console.log('%cprev state', 'color:green', prevState)
 console.log('%caction', 'color:blue', action)
 
 const returnValue = next(action)
 
 const nextState = getState()
 console.log('%cnext state', 'color:green', nextState)
 console.groupEnd('reducer')
 return returnValue
 }
 }
 
 
 |