美文网首页
redux-thunk

redux-thunk

作者: Poiey | 来源:发表于2019-12-26 09:24 被阅读0次

redux-thunk 是一款redux中间件

工作流程

  1. 目前是先处理异步在派发动作
  2. 使用 redux-thunk 之后,我们可以让一个动作直接编程异步的代码
  3. 默认情况下,store.dispatch() 这个方法只能接受到 一个普通的动作对象
  4. 使用 redux-thunk 之后,store.dispatch() 不光可以接受普通的动作对象,还可以接受异步的动作(函数)
  5. plain object 普通动作对象
  6. async action 异步动作(函数)
  7. async action 异步动作函数,会自动接收到两个参数,分别是 dispath 与 getState
    1. dispatch 就是 store.dispatch 的引用
    2. 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

相关文章

网友评论

      本文标题:redux-thunk

      本文链接:https://www.haomeiwen.com/subject/juhkoctx.html