Redux工具包以dispatch和getState作为参数的调度操作,与使用函数增强器的简单redux实现相同

9bfwbjaz  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(183)

很长一段时间以来,我一直在使用带有此函数增强器的简单redux:

const asyncFunctionMiddleware = storeAPI => next => action => {
  // If the "action" is actually a function instead...
  if (typeof action === 'function') {
    // then call the function and pass `dispatch` and `getState` as arguments
    return action(storeAPI.dispatch, storeAPI.getState)
  }

  // Otherwise, it's a normal action - send it onwards
  return next(action)
}

一旦在创建存储时将其添加到applyMiddleware,您就可以简单地将其用作:

// Write a function that has `dispatch` and `getState` as arguments
const stateBasedLotOfDispatches = (dispatch, getState) => {
  // Lot of conditions based on current state -> getState
  // get arguments to pass to action1
  // create payload for action2
  dispatch(action1())
  dispatch(action2())
  ...
}

我搜索了很多关于如何用redux工具包做这件事,但找不到一种方法,或者可能错过了一些关于redux工具包的基本知识,希望有人能给我指出正确的方向。
需要添加1更多的东西,函数调用将不会是asyncThunk类型,所以我不需要它是异步的。

inkz8wg9

inkz8wg91#

这就是redux-thunk中间件,Redux Toolkit已经自动启用了这个中间件。
你可以继续和dispatch(stateBasedLotOfDispatches),它会工作。

相关问题