【发布时间】:2026-01-01 05:35:01
【问题描述】:
我在我的 Reactjs 应用程序中使用 Flux 和 WebSocket,在实施过程中我遇到了一些问题。
问题:
假设我有一组 actioncreator 和一个存储来管理 WebSocket 连接,并且连接是在 actioncreator (
open(token)) 中启动的,我应该把我的conn.emit放在哪里以及如何让其他操作访问我的连接对象,以便它们可以将数据发送到后端?我是否必须将它作为参数传递给视图中调用的操作(例如
TodoActions.create(conn, todo)),还是有更聪明的方法?
我正在使用 ES6 类。
如果我在要点中遗漏了任何必要的内容,请告诉我。
编辑:
这是我迄今为止根据 glortho 的回答炮制出来的:
import { WS_URL } from "./constants/ws";
import WSActions from "./actions/ws";
class WSClient {
constructor() {
this.conn = null;
}
open(token) {
this.conn = new WebSocket(WS_URL + "?access_token=" + token);
this.conn.onopen = WSActions.onOpen;
this.conn.onclose = WSActions.onClose;
this.conn.onerror = WSActions.onError;
this.conn.addEventListener("action", (payload) => {
WSActions.onAction(payload);
});
}
close() {
this.conn.close();
}
send(msg) {
return this.conn.send(msg);
}
}
export default new WSClient();
【问题讨论】:
标签: javascript websocket reactjs flux