websocket socket.on()回调调用了两次

vq8itlhq  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(308)

有人能帮助我或者解释为什么socket.on的回调被调用了两次吗?我使用的是socket.iosocket.io-client版本4.5.1。我试图把socket.on放在useEffect中,但是回调的调用减少到了两次。下面是代码:
委托人:

import { useEffect, useState } from 'react'
import { io } from 'socket.io-client';

const socket = io('ws://localhost:3001');

const Main = () => {
  const [message, setMessage] = useState<string>('');
  const [chat, setChat] = useState<string[]>([]);

  useEffect(() => {
    socket.on('recv_broadcast', message => { // this callback is being called twice
      console.log(message);
      setChat(state => [...state, message]);
    });
  }, []);

  const send = () => {
    setChat(state => [...state, message]);
    socket.emit('send_broadcast', message);
  }
...

伺服器:

io.on('connection', socket => {
  console.log('Client connected');
  console.log('Total client:', io.engine.clientsCount);

  socket.on('send_broadcast', message => {
    socket.broadcast.emit('recv_broadcast', message);
  })
});
anauzrmj

anauzrmj1#

React Strict模式会将某些函数运行两次,这意味着它会添加recv_broadcast侦听器两次!
进入index.js文件并删除

<React.Strictmode> </React.Strictmode>

缐条。
希望这对你有帮助!

相关问题