最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - redux middleware -> interceptblocktransform? - Stack Overflow

programmeradmin4浏览0评论

we're running a SPA. dispatched actions (not ponents) are auth-based.

is it possible to intercept and transform dispatched actions?

i.e.

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

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

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

else continue

note that 'FOO' should never hit a reducer

we're running a SPA. dispatched actions (not ponents) are auth-based.

is it possible to intercept and transform dispatched actions?

i.e.

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

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

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

else continue

note that 'FOO' should never hit a reducer

Share Improve this question asked Mar 18, 2017 at 2:19 Anthony ChungAnthony Chung 1,4772 gold badges25 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Yes, that is absolutely one of the intended use cases for middleware. Any middleware can inspect and modify any action going through the pipeline before it reaches the reducers, and even prevent an action from continuing on.

You may want to read through the Middleware page in the Redux docs, as well as the articles in the Redux Middleware category in my React/Redux links list. Those should give you a better idea how middleware work, and how you can use them.

Why not let that action hit the reducer and ignore it there?
(best option IMO)

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

If you do this through your middleware, you'd need to decide if you want to send that action to the reducer or not:

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 
    } 
  }
}
发布评论

评论列表(0)

  1. 暂无评论