如何解决从 redux 中间件返回 2 个动作
我正在开发一个使用 Redux 进行状态管理的 React Native 项目。它还使用 socket.io 进行实时通信,因此它有一个 socketIoMiddleware
负责与服务器的通信。有一个 emitPromise
fn,它基本上将 socket.emit
包装在一个 promise 中,然后使用来自服务器的答案进行解析。
现在,如果用户尚未通过身份验证(并且套接字已打开),那么我不会向服务器发送任何内容,而是将信息存储在我的中间件中。当用户获得身份验证时(经过特殊调用),然后我尝试将信息发送到服务器。问题是那时我的 action
与我需要发送到服务器的不同。
export default function createSocketIoMiddleware(socket) {
...
return (store) => {
socket.on('connect',() => {
store.dispatch({
type: CONNECT_SOCKET,});
});
...
return (next) => (action) => {
...
if (!action.type.startsWith(SOCKET_PREFIX)) {
if (action.type === AUTHENTICATION) {
isAuth = true;
return next(action);
}
if (lastCommand && isAuth) {
const tmp = lastCommand;
const tmpMeta = lastCommandMeta;
lastCommand = null;
lastCommandMeta = null;
// here is the problem
return next({
type: channel,Meta: action.payload,payload: emitPromise(socket,channel.toLowerCase(),action.payload || {}),});
// return next(action);
}
return next(action);
}
const channel = action.type.slice(SOCKET_PREFIX.length);
if (isAuth === false && channel !== XXX) { // at this point if the user is not auth,I store the action instead of sending it
lastCommand = channel;
lastCommandMeta = action.payload;
return undefined;
}
return next({
type: channel,});
};
};
}
因此,如果 lastCommand
存在且 isAuth
为真,那么我将命令发送到服务器。问题是我不确定如何将 lastCommand
发送到服务器,同时返回要由减速器处理的操作。
如果我现在按照代码中的方式返回它,那么我会丢失一个已调度的操作(它被返回的 lastCommand
发射所取代)。如果我注释掉 emitPromise
指令,那么显然有一条信息我不会发送到服务器。
我也试过这样做:
...
if (lastCommand && isAuth) {
const tmp = lastCommand;
const tmpMeta = lastCommandMeta;
lastCommand = null;
lastCommandMeta = null;
next({
type: tmp,Meta: tmpMeta,tmp.toLowerCase(),tmpMeta || {}),});
return next(action);
}
...
所以不返回第一个 next
然后返回第二个,但在阅读之后,我的理解是我们必须始终 return next(action)
,我不确定这样是否能正常工作。
在此先感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。