通量和 WebSocket

Flux and WebSockets

我在我的 Reactjs 应用程序中使用 Flux 和 WebSocket,在实施过程中我遇到了一些问题。

问题:

Current code is here

我正在使用 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();

您应该有一个单例模块(不是商店或动作创建者)来处理打开套接字和引导流量通过。然后任何需要通过套接字 send/receive 数据的动作创建者只需要模块并使用它的通用方法。

这是一个未经测试的快速但肮脏的示例(假设您使用的是 CommonJS):

SocketUtils.js:

var SocketActions = require('../actions/SocketActions.js');

var socket = new WebSocket(...);

// your stores will be listening for these dispatches
socket.onmessage = SocketActions.onMessage;
socket.onerror   = SocketActions.onError;

module.exports = {
  send: function(msg) {
    return socket.send(msg);
  }
};

MyActionCreator.js

var SocketUtils = require('../lib/SocketUtils.js');

var MyActionCreator = {
  onSendStuff: function(msg) {
    SocketUtils.send(msg);
    // maybe dispatch something here, though the incoming data dispatch will come via SocketActions.onMessage
  }
};

当然,在现实中您会做得更好,而且会有所不同,但这会让您了解如何构建它。