[英]Design for Websocket with React + Redux
我正在尝试使用 React + Redux 实现 Websocket 通信。 问题是一种范围的设计。
以下代码是我编写的源代码的一部分。
在此页面中,1. Init Socket Settings ⇒ 2. Start Socket ⇒ 3. Execute Event ⇒ 4. Receive Socket
当我执行事件时,我可以接收 websocket 数据,但是我不知道如何最好地定位这些方法。
我的问题是我想知道设计的最佳实践。 当然,我想利用Redux的设计。 如果您有更好的主意,那么使用诸如 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);
socket
和channel
的最佳位置在哪里?
如果您需要将 Web 套接字详细信息存储到 redux,请在此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.