node.js - React 中的 Socket.io 一次后不听
问题描述
我有两个组件,它们都是分开的。我必须通过套接字将数据从组件 1 发送到组件 2。但是我的 component2 只侦听一次事件,一次之后它不再侦听事件
组件1
class Component extends React.component{
socket = socketIOClient("http://localhost:5000")
sendData = () =>{
socket.emit("newData", {somedata})
}
render() {
return(
<button onClick={this.sendData} >Send</button>
})
}
组件2
class Component2 extends React.Component{
constructor(props) {
super(props)
this.state = {data}
}
socket = socketIOClient("http://localhost:4000")
componentDidMount() {
socket.on("newData", data =>
this.setState(data)
)}
render(){
return(<h1>{this.state.data.someAttribute} <h1/>)
}
}
服务器
const io = socketIO(server)
io.on("connection", socket =>{
socket.on("newData", data=> socket.emit("newData"))
})
Component1 正在向服务器发送任意次数的数据(通过控制台登录服务器验证)但 Component2 仅在第一次接收数据。
解决方案
找到了解决办法,
错误在服务器端。
我们必须使用实际的 io 对象将事件发送到连接到服务器的其他套接字。
所以服务器端将是,
const io = socketIO(server)
io.on("connection", socket =>{
socket.on("newData", data =>{
io.sockets.emit("newData", data) //changed this line
})
})
推荐阅读
- java - 测试容器:服务就绪后同步日志
- git - 如何使用 cli 获取关于当前分支的 Github 最新提交 url
- python - 烧瓶应用程序在heroku上抛出未找到错误
- java - ESAPI中关于Java(Springboot)的XSS预防在web上显示实体中文代码
- docker - 如何跟踪日志直到在 PowerShell 中匹配字符串
- c++ - 带有 WTSEnumerateSessionsEx 的 C6387 警告
- python - 如何在 tkinter 中将新按钮添加到默认窗口管理器的控件中?
- java - 如何通过静态出口 IP 从 Cloud Run 连接到 Cloud SQL 和外部流量?
- list - 有人可以解释为什么我不能将变量分配为反向列表吗?
- reactjs - 当子级需要父级先前状态时,如何拆分嵌套的 setStates?