有人能帮助我或者解释为什么socket.on
的回调被调用了两次吗?我使用的是socket.io
和socket.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);
})
});
1条答案
按热度按时间anauzrmj1#
React Strict模式会将某些函数运行两次,这意味着它会添加
recv_broadcast
侦听器两次!进入index.js文件并删除
缐条。
希望这对你有帮助!