这是我第一次在生产中使用socket.io
。我正在使用React
+ Redux
。我最近将socket.io
与redux集成并且工作正常,但我不确定这是否是我做得最好的方法。因为我还没有找到任何有关redux的socket.io的正确实现,我需要一些帮助/建议,如果我可以改进它。
因此,对于初学者,我已经设置了一个服务来管理整个应用程序的套接字:
Socket.js
import isEmpty from 'lodash/isEmpty';
import io from 'socket.io-client';
import storage from '../storage';
/* eslint-disable no-use-before-define */
const Socket = {
connect,
emit,
on,
removeListener,
socket: null
};
/* eslint-enable no-use-before-define */
function connect() {
const hasAuthenticated = !isEmpty(storage.get('user'));
if (hasAuthenticated) {
// Setup a server for testing.
Socket.socket = io.connect('http://localhost:3000', { reconnect: true });
}
}
connect();
function on(eventName, callback) {
if (Socket.socket) {
Socket.socket.on(eventName, data => {
callback(data);
});
}
}
function emit(eventName, data) {
if (Socket.socket) {
Socket.socket.emit(eventName, data);
}
}
function removeListener(eventName) {
if (Socket.socket) {
Socket.socket.removeListener(eventName);
}
}
export default Socket;
我只用了一页,但是当然会有更多的页面。我的页面的redux组合是:
Dashboard.jsx
componentWillMount() {
this.props.alertViolations(); // Action
}
componentWillUnmount() {
this.props.unsubscribeViolations(); // Action
}
Actions.js
export function alertViolations() {
return dispatch => {
Socket.on('violations', violation => {
dispatch(actions.updateViolations(violation));
});
};
}
export function unsubscribeViolations() {
Socket.removeListener('violations');
return dispatch => {
dispatch(actions.removeViolationsListener());
};
}
工作正常。在卸载时,它会停止侦听我在服务器上的emit函数。如果我能得到一些建议,我将非常感激:
connect
和
disconnect
功能? 非常感谢。如果我在解释中遗漏了任何内容,请告诉我。
答案 0 :(得分:5)
中间件是Redux应用中像websocket这样的持久连接最常见的地方。已经有大量现有的Redux + websocket集成库 - 请参阅我在https://github.com/markerikson/redux-ecosystem-links/blob/master/middleware.md#sockets-and-adapters的列表。您可以按原样使用其中一些,或将它们用作您自己实现的示例。