使用 ReactJS ES6 实现 Socket.io [英] Implementing Socket.io with ReactJS ES6

查看:91
本文介绍了使用 ReactJS ES6 实现 Socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将 SocketIO 客户端合并到我的项目中时遇到了麻烦,因为我以同构方式设置了项目.在我的基本 html 中包含套接字文件后,我尝试在我的一个组件的 componentdidmount 中调用 let socket = io(); 但是最初在我的控制台中记录它之后它是未定义的.当我路由到另一个组件并使用该套接字变量返回到该组件时,它会填充一些数据.我想我的意思是它没有在我的组件中初始化套接字是什么,它似乎必须等待我如何解决这个问题?

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?

组件.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.

推荐答案

可能还有其他解决方案,但以下对我有用:

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

1) npm 安装 socket 客户端包

2) 将 socket 导入到所有需要 socket 功能的组件的最根组件中

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

3) 在生命周期事件之一 (constructor/componentWillMount, componentDidMount) 中连接服务器端套接字事件监听器

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

4) 如果在子组件中处理某些服务器事件有意义,则通过 props 传递套接字对象

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

示例:

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

这篇关于使用 ReactJS ES6 实现 Socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆