node.js 使用 ReactJS ES6 实现 Socket.io

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34480703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:41:54  来源:igfitidea点击:

Implementing Socket.io with ReactJS ES6

node.jsreactjssocket.io

提问by Karan

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?

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

Component.jsx

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

顺便说一句,对于从服务器连接之类的东西,这很好用,它发出用户正在连接和断开服务器的信息,只是客户端操作让我感到困惑。

回答by azium

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

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

1) npm install the socket client side package

1) npm 安装socket客户端包

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

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

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

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

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

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

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

回答by gedhean

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

回答by Mario Legenda

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

我在 socket.io 和 React 上遇到了同样奇怪的问题。我想从我的 main.jsx 文件中确定一条清晰的依赖注入线,并带有到其他组件的道具。原来我只需要像这样初始化io...

const socket = window.io();

And that was it. It worked.

就是这样。有效。