简体   繁体   中英

Apply middleware to a single store

In redux, you can easily create a middleware. I have one that looks like this, which is easy to apply to my entire store.

function socketMiddleware(store) {
  const socket = io.connect(SOCKET_URL);
  socket.on('connect', () => store.dispatch({ type: CONNECTED }));

  return next => action => {
    // does something with the socket.
  }
}

However, I want to provide a middleware which only runs on a single reducer in my store, whenever an action is dispatched that updates that reducer. That is:

export default wrapWithMiddleware((state = INITIAL_STATE, action) => {
  switch (action.type) {
    default:
      return state;
  }
})

is this possible in redux?

Middleware does what middleware does: Process every request (in this case actions), before they reach their endpoint (reducers), or are halted by the middleware for some reason.

So you need to make sure your middleware can identify your actions in some way. For instance redux-thunk identifies actions by checking if they are a function, and redux-form uses a prefix for its action-types (something along the lines of @REDUX_FORM/YOUR_ACTION_NAME ). This is the way you should be thinking, because otherwise it would defy the purpose of middleware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM