Set up React component to listen to socket.io

好久不见. 提交于 2019-12-24 01:06:37

问题


I want my React component 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 component'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 component connect through socket.io to the server? Thanks.


回答1:


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();
  }
  ...
}



回答2:


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




回答3:


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

componentWillMount() {
  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 })
  });
}


来源:https://stackoverflow.com/questions/39187049/set-up-react-component-to-listen-to-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!