我正在尝试创建我的第一个 Redux 中间件来处理与聊天服务器的持久 Socket.IO 连接。Redux 应用程序只应在用户登录后创建 Socket.IO 连接。store.user.id
在 Redux 商店中,null
如果用户已登录,则不会。
问题:如何创建 Socket.IO 仅在用户登录时连接,在用户注销时断开连接?
在下面的示例代码中,立即建立了 Socket.IO 连接。
import io from 'socket.io-client';
const chatMiddleware = () => {
return store => {
// HOW TO Connect to socketio server only after being logged in?
const socket = io('http://localhost:3002');
socket.on('connect', () => {
console.log('Connected to chat server.');
socket.emit('msg', 'hello world!');
});
return next => action => {
if (action.type == SEND_MESSAGE) {
console.log('middleware intercepted SEND_MESSAGE')
socket.emit('msg', action.payload);
return;
}
return next(action);
}
}
}
export default chatMiddleware
系统环境
- 反应-dom@16.13.1
- react-redux@7.2.0
- 反应@16.13.1
- redux@4.0.5
- 节点 v14.0.0