获取状态并从中间件进行调度

Get state and make dispatch from middleware

在我的 React 应用程序中,我使用了长轮询 API。为了在每次响应时自动发送请求,我使用了中间件。但在发送新请求之前,我必须将收到的数据保存在商店中。不仅如此,我还想在我的中间件中发送另一个动作。所以我的结构是这样的:

InitLongPoll() -> SendRequest(数据) -> ReceiveResponse(数据)* -> SendRequest(数据)

'*' 是我的中间件。从那里我使用 store.dispatch(responseData) 将数据保存到商店并使用 store.dispatch(sendRequest(authData)) 发送新请求。

可以使用 store.getState().authReducer 接收 authData 吗?据我所知,我的中间件应该是一个纯函数,不应该依赖于外部数据(存储)。提前致谢。

Is it okay to receive that authData using store.getState().authReducer? As far as i know, my middleware should be a pure function and shouldn't depend on external data (store).

是的。中间件是在redux循环中引入副作用的方式,不能是纯函数。你自己的中间件有一个副作用——轮询服务器。

一个redux中间件是anti-thesis一个纯函数,定义为:

  1. The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices (usually—see below).
  2. Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices (usually—see below).

您还可以在 redux-thunk 源代码中看到,它使用 getState:

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}