Implementing Socket.io with ReactJS ES6

前端 未结 3 1616
孤街浪徒
孤街浪徒 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 (
          <Child 
            socket = { socket } 
            sendMessage = { this.sendMessage }
          />
        )
      }
    }
    
    0 讨论(0)
  • 2021-01-30 15:11

    You can instantiate a socket outside of the component and use it inside the component. Like this:

    import React, { Component } from 'react'  
    import io from 'socket.io-client'
    
    var socket = io()
    
    class MyComponent extends Component {
        componentDidMount() {
            // You can use the socket inside the componet
            socket.on('message', msg => console.log(msg))
        }
    }
    
    0 讨论(0)
  • 2021-01-30 15:15

    I had the same weird problem with socket.io and React. I wanted to determine a clear line of dependency injection with props to other components from my main.jsx file. Turned out that I only had to initialize io like this...

    const socket = window.io();
    

    And that was it. It worked.

    0 讨论(0)
提交回复
热议问题