最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set up React component to listen to socket.io - Stack Overflow

programmeradmin1浏览0评论

I want my React ponent to listen to events from socket.io. My code works if I have the HTML files include:

<script src="socket.io/socket.io.js"></script>

and then the ponent's constructor() has:

this.socket = io(); // eslint-disable-line no-undef

The HTML file retrieves the proper socket.io client code from my Express server, and everything's fine.

But this feels so cheesy. I hate to rely on the global window name space to find the io() function. What's the best practice for letting a React ponent connect through socket.io to the server? Thanks.

I want my React ponent to listen to events from socket.io. My code works if I have the HTML files include:

<script src="socket.io/socket.io.js"></script>

and then the ponent's constructor() has:

this.socket = io(); // eslint-disable-line no-undef

The HTML file retrieves the proper socket.io client code from my Express server, and everything's fine.

But this feels so cheesy. I hate to rely on the global window name space to find the io() function. What's the best practice for letting a React ponent connect through socket.io to the server? Thanks.

Share Improve this question asked Aug 28, 2016 at 0:46 richb-hanoverrichb-hanover 1,0912 gold badges14 silver badges24 bronze badges 2
  • Can't you pass the io function in props? And then connect during ponentDidMount – rossipedia Commented Aug 28, 2016 at 3:02
  • That would help in testing to, as you could pass in a mock io function that you control. – rossipedia Commented Aug 28, 2016 at 3:02
Add a ment  | 

3 Answers 3

Reset to default 5

If you're using a bundler like Webpack or Browserify, you can use socket.io-client.

For instance:

const io = require('socket.io-client');

class MyComponent extends React.Component {
  constructor(...args) {
    super(...args);
    this.socket = io();
  }
  ...
}

I would create the socket on ponentWillMount and setState on the desired event callback.

Thanks for sharing. I used the ponentWillMount method. I also added a connection detection:

ponentWillMount() {
  const socket = io(uri)

  socket.on('update', (data) => {
    this.setState({ data, connected: true })
  });

  socket.on('disconnect', () => {
    this.setState({ connected: false })
  });

  socket.on('reconnect', () => {
    this.setState({ connected: true })
  });
}
发布评论

评论列表(0)

  1. 暂无评论