redux-thunk 是一款redux中间件
工作流程
- 目前是先处理异步在派发动作
- 使用 redux-thunk 之后,我们可以让一个动作直接编程异步的代码
- 默认情况下,store.dispatch() 这个方法只能接受到 一个普通的动作对象
- 使用 redux-thunk 之后,store.dispatch() 不光可以接受普通的动作对象,还可以接受异步的动作(函数)
- plain object 普通动作对象
- async action 异步动作(函数)
- async action 异步动作函数,会自动接收到两个参数,分别是 dispath 与 getState
- dispatch 就是 store.dispatch 的引用
- getState 就是 store.getState 的引用
实现原理
const next = store.dispatch
store.dispatch = (action) => {
// 判断当前这个 action 动作是 plain Ojbect 还是 async action
if (typeof action === 'function') {
action(store.dispatch, store.getState)
} else {
next(action)
}
}
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
))
export default store
网友评论