Implementing Socket.io with ReactJS ES6

2019-01-31 02:02发布

问题:

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 let socket = io(); in the componentdidmount of one of my components however initially after logging it in my console it is undefined. When I route to a different component and comeback to that component with that socket variable then it becomes filled with some data. I guess my point here it isn't initializing in my component what socket is, it seems like it has to wait how do I work around this?

Component.jsx

componentDidMount() {
    let socket = io();
    console.log(socket);
  }

Base.html

<!doctype html>
<html lang="">

<head>
    <title>TITLE</title>

    META

    LINK

</head>

<div class="app">CONTENT</div>

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-XXXXX-X', 'auto');
    ga('send', 'pageview');
</script>
<script type="text/javascript" charset="utf-8" src="/assets/app.js"></script>

<script src="/socket.io/socket.io.js"></script>
<script>
        var socket = io();
</script>

</body>
</html>

This works fine btw I for stuff like on connect from the server, it emits that a user is connecting and disconnecting off the server, just the client manipulation has me puzzled.

回答1:

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 }
      />
    )
  }
}


回答2:

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.



回答3:

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))
    }
}