首页 > 解决方案 > 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 仅在第一次接收数据。

标签: node.jsreactjssocketswebsocket

解决方案


找到了解决办法,

错误在服务器端。

我们必须使用实际的 io 对象将事件发送到连接到服务器的其他套接字。

所以服务器端将是,

const io = socketIO(server)
io.on("connection", socket =>{
    socket.on("newData", data =>{
        io.sockets.emit("newData", data) //changed this line
   })

})


推荐阅读