简体   繁体   English

将中间件应用于单个商店

[英]Apply middleware to a single store

In redux, you can easily create a middleware. 在redux中,您可以轻松创建中间件。 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? 在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 ). 例如, redux-thunk通过检查动作是否为函数来标识动作,而redux-form为其动作类型使用前缀(类似于@REDUX_FORM/YOUR_ACTION_NAME )。 This is the way you should be thinking, because otherwise it would defy the purpose of middleware. 这就是您应该考虑的方式,因为否则它将违背中间件的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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