在Reactjs上收听socket.io服务器时如何setState()?
我开发了一个socket.io服务器,该服务器每10秒将数据发送给客户端。 socket.io客户端用于我使用ReactJS类组件创建的应用程序。我连接到componentDidmount
中的套接字,并在componentDidupdate
中收听了套接字。
let socket = null
class Map extends Component {
constructor(props) {
super(props)
this.state= {
stateData: null
}
}
componentDidMount() {
socket = io.connect('http://localhost:8080');
// calling some method
}
componentDidUpdate( {
if(socket !== null) {
socket.on("positionUpdates", (data) => {
// console log to check if the data was connected successfully and the time when it got the data
console.log("connected", data, new Date())
this.setState({stateData: data})
})
}
}
render() {
return (
)
}
}
我将使用setState()
将我从套接字中获得的数据保存到状态。但是在运行代码时,我遇到了一件奇怪的事情。我在socket.on
之后做了console.log
。 console.log
应在检索数据时每10秒发生一次。但是发生的是console.log
多次显示。当我删除setState
时,代码通常会再次运行。
在socket.io client上收听socket.io服务器时,我应该如何做setState
?
I developed a socket.io server that sends data every 10 seconds to the client. Socket.io client is used in an application that I created with ReactJs class component. I connected to the socket in componentDidMount
and listened for the socket in componentDidUpdate
.
let socket = null
class Map extends Component {
constructor(props) {
super(props)
this.state= {
stateData: null
}
}
componentDidMount() {
socket = io.connect('http://localhost:8080');
// calling some method
}
componentDidUpdate( {
if(socket !== null) {
socket.on("positionUpdates", (data) => {
// console log to check if the data was connected successfully and the time when it got the data
console.log("connected", data, new Date())
this.setState({stateData: data})
})
}
}
render() {
return (
)
}
}
I will save the data that I get from the socket into a state using setState()
. But I ran into a strange thing when running the code. I made a console.log
after socket.on
. console.log
should happen once every 10 seconds when the data is retrieved. But what happens is that the console.log
is displayed multiple times. When I remove the setState
, the code normally runs again.
How should I do setState
when listening to socket.io server on socket.io client?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,从我对socket.io的侦听器上的理解中,您可以收听相同的事件,但具有不同的功能。
因此,您可以做类似的操作
,因此每次设置状态后
componentDidupdate
被触发并socket.on(“ positionupdates”,(data)=> {... {...})
多次注册positionupdates
事件。因此,要修复此操作,将您的
socket.on
s移至componentdidmount,并确保在卸载后离开侦听器。So from my understanding of socket.io's
on
listener, is that you can listen the same event but with different functions.So you can do something like
So after everytime you set state the
componentDidUpdate
gets fired andsocket.on("positionUpdates", (data) => {...})
registers thepositionUpdates
event multiple times.So to fix this move your
socket.on
s to componentDidMount and also make sure to off the listener after unmount.