在学习redux的时候使用到了redux-thunk,redux-thunk是用于redux异步请求(类似于vue中的action)的中间件,redux的dispatch只能传入对象,因此传入函数的时候我们需要判断一下,看传入的是否是函数,如果是函数的话得先执行函数(promise),然后等状态完成再进行dispatch。
日志打印
function log(store) {
const next = store.dispatch
function logDispatch(actions) {
console.log('派发action', actions)
next(actions)
console.log('得到result', store.getState())
}
store.dispatch = logDispatch
}
redux-thunk
function thunk(store) {
const next = store.dispatch
function thunkDispatch(action) {
if (typeof actions === 'function') {
// 这里没有使用next是因为 action里面可能也是套函数的
action(store.dispatch, store.getState)
} else {
// 没有函数就使用之前的dispatch
next(action)
}
}
store.dispatch = thunkDispatch
}
thunk(store)