简体   繁体   English

使用 React + Redux 设计 Websocket

[英]Design for Websocket with React + Redux

I am trying to implement Websocket communication with React + Redux.我正在尝试使用 React + Redux 实现 Websocket 通信。 The question is kind of design of scope.问题是一种范围的设计。

The following code is part of source code I wrote.以下代码是我编写的源代码的一部分。

In this page, 1. Init Socket Settings ⇒ 2. Start Socket ⇒ 3. Execute Event ⇒ 4. Receive Socket在此页面中,1. Init Socket Settings ⇒ 2. Start Socket ⇒ 3. Execute Event ⇒ 4. Receive Socket

When I execute event, I can receive the websocket data, however I have no idea how to locate these method for the best.当我执行事件时,我可以接收 websocket 数据,但是我不知道如何最好地定位这些方法。

My question is I would like to know the best practice of design.我的问题是我想知道设计的最佳实践。 Of corse, I would like to make use of the design of Redux.当然,我想利用Redux的设计。 If you have better idea, it doesn't matter to use other modules like reducer or actions.如果您有更好的主意,那么使用诸如 reducer 或 actions 之类的其他模块都没有关系。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Socket } from 'phoenix';

//Init Socket Settings 
const socket = new Socket("/socket", {params: {token: window.userToken}});
socket.connect();
const channel = socket.channel("member:lobby", {});

//Receive Socket 
channel.on('new_message', state => {
    console.log("Receive Socket!!!" + state.body);
});


class Sample extends Component{
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }

        this.doEnterKey = this.doEnterKey.bind(this);
    }

    componentDidMount() {
        //Start Socket
        channel.join()
            .receive("ok", resp => { console.log("Joined successfully", resp) })
            .receive("error", resp => { console.log("Unable to join", resp) })
    }

    //Execute Event
    doEnterKey(e){
        if(e.keyCode === 13){
            console.log('Enter Key!!!' + e.target.value);
            channel.push("new_message", {body: e.target.value});
        }
    }

    render() {
        return (
            <div>
                <div>Websocket</div>
                <div id="messages"></div>
                <input id="chat-input" type="text" onKeyDown={this.doEnterKey}></input>
            </div>
        );
    }
}
export default connect()(Sample);

Where is the best place to location for socket and channel ? socketchannel的最佳位置在哪里?

Here if you need to store web socket details to the redux.如果您需要将 Web 套接字详细信息存储到 redux,请在此处。

  1. Create action and reducer创建动作和减速器
  2. Call the action on the receive function with response data.使用响应数据调用接收函数上的操作。
  3. Update the reducer.更新减速器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM