admin管理员组文章数量:1318156
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 duringponentDidMount
– 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
3 Answers
Reset to default 5If 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 })
});
}
本文标签: javascriptSet up React component to listen to socketioStack Overflow
版权声明:本文标题:javascript - Set up React component to listen to socket.io - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742043555a2417658.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论