redux 中间件 -> intercept/block/transform?

redux middleware -> intercept/block/transform?

我们是 运行 SPA。分派的操作(不是组件)是基于身份验证的。

是否可以拦截和转换派发的动作?

dispatch({
    type: 'FOO',
    payload: { some: value }
})

function magicMiddleware(action) => decide if authorized. 
if no...

dispatch({
    type: 'BAR',
    payload: { new: value }
})

else continue

请注意,'FOO' 永远不要碰到减速器

是的,这绝对是中间件的预期用例之一。任何中间件都可以在到达减速器之前检查和修改通过管道的任何操作,甚至可以阻止操作继续进行。

您可能需要通读 Middleware page in the Redux docs, as well as the articles in the Redux Middleware category in my React/Redux links list。这些应该能让您更好地了解中间件的工作原理以及如何使用它们。

为什么不让那个 action 命中 reducer 而忽略它呢?
(IMO 的最佳选择)

switch (action.type) {
  case SOMETHING_NOT_FOO:
    return Object.assign({}, state, {
      whatever other new object here...
  })
  default:
    return state
}

如果您通过中间件执行此操作,则需要决定是否要将该操作发送到减速器:

function yourMiddleware(nextDispatch) {
  return function(action) {
    // do stuff
    if (action.type !== 'FOO') {
      return nextDispatch(action);
    } else {
      return nextDispatch({type: 'dummy'}); // need to send an action 
    } 
  }
}