在我的 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 中间件是纯函数的对立面,其定义为:
- 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).
- 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);
};
}
关于reactjs - 获取状态并从中间件进行调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683615/