简体   繁体   English

Socket.io 与 React 和 Node.js

[英]Socket.io with React and Node.js

I'm kinda new using sockets.io and I have a pretty basic question.我有点新使用 sockets.io 我有一个非常基本的问题。

I have this code on the server side where I basically try to listen for the event called setName and I pass the username parameter and I emit a new event called "setNameCb" to the client side.我在服务器端有这段代码,我基本上尝试侦听名为 setName 的事件,并传递用户名参数,并向客户端发出一个名为“setNameCb”的新事件。

io.on("connection", (socket) => {
  socket.on("setName", (username) => {
    socket.emit("setNameCb", username);
  });
});

And this code on the client side where I try to pass an username when the button is clicked.而这个代码在客户端我尝试在单击按钮时传递用户名。 After that I listen for the setNameCb event from the server side and I try to get the username value.之后,我从服务器端监听 setNameCb 事件并尝试获取用户名值。

const setNameFunction = () => {
  socket.emit("setName", "Cristian");
};
socket.on("setNameCb", (username) => {
  alert(username);
});

return (
  <div className="App">
    <button onClick={setNameFunction}>set name</button>
  </div>
);

Alright, eveything is working, but the problem is that I get multiple alerts with the username and I just can't figure it out why that is happening.好吧,一切都在工作,但问题是我收到了多个带有用户名的警报,我就是不知道为什么会这样。

I'd really appreciate an explanation for this one.我真的很感激对此的解释。 I know it's a very basic question but that will help me to understand better the concept.我知道这是一个非常基本的问题,但这将帮助我更好地理解这个概念。

Thank you a lot!十分感谢!

The socket listener in react component is created on every render, if not wrapped into useEffect.如果没有包装到 useEffect 中,react 组件中的套接字侦听器会在每次渲染时创建。

useEffect(() => {
     const setNameFunction = () => {
     socket.emit("setName", "Cristian");
   };
   socket.on("setNameCb", (username) => {
     alert(username);
   });
   }, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM