Implementing Socket.io with ReactJS ES6

前端 未结 3 1746
孤街浪徒
孤街浪徒 2021-01-30 14:39

I\'m having trouble incorporating SocketIO client into my project as I have me project set up isomorphically. After including the socket file in my base html, I try to call

3条回答
  •  天命终不由人
    2021-01-30 15:06

    There are likely other solutions, but the following works for me:

    1) npm install the socket client side package

    2) import socket into the most root component of all components that need socket functionality

    3) hookup server side socket event listeners in one of the lifecycle events (constructor / componentWillMount, componentDidMount)

    4) pass down socket object through props if it makes sense to handle certain server events in child components

    example:

    import io from 'socket.io-client'
    let socket = io(`http://localhost:8000`)
    
    class App extends Component {
      state = { data: {} }
    
      componentDidMount() {    
        socket.on(`server:event`, data => {
          this.setState({ data })
        })
      }
    
      sendMessage = message => {
        socket.emit(`client:sendMessage`, message)
      }
    
      render () {
        return (
          
        )
      }
    }
    

提交回复
热议问题