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

问题:

  • 假设我有一组 Action 创建者和一个用于管理WebSocket连接的商店,并且该连接是在一个 Action 创建者(open(token))中启动的,应该在哪里放置我的conn.emit以及如何让其他 Action 访问我的连接对象,以便他们可以将数据发送到后端?
  • 我是否必须将其作为参数传递给 View 中调用的操作(例如TodoActions.create(conn, todo)),还是有更聪明的方法?

  • 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();
    

    最佳答案

    您应该有一个单例模块(不是商店或 Action 创建者)来处理打开套接字并引导流量通过的模块。然后,任何需要通过套接字发送/接收数据的 Action 创建者都只需要模块并利用其通用方法即可。

    这是一个快速且肮脏的未经测试的示例(假设您使用的是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
      }
    };
    

    当然,实际上,您会做得更好而又有所不同,但这使您对如何组织它有所了解。

    09-25 18:23
    查看更多