【发布时间】:2021-06-04 15:52:05
【问题描述】:
问题:我有以下反应组件。基本上,我正在构建一个与 socket.io 反应的聊天应用程序
import { io } from 'socket.io-client';
const socket = io(ServerEndURL);
export default function Chat (props) {
const uuid = props.uuid;
const classes = useStyles();
const [open, setOpen] = useState(false);
const [btnColor, setBtnColor] = useState('white');
const [activeStatus, setActiveStatus] = useState('Offline');
const [unreadMsgs, setUnreadMsgs] = useState(0);
const [msgArr, setMsgArr] = useState([]);
const chatBtnRef = useRef();
const chatBoxRef = useRef();
const msgInputRef = useRef();
useEffect(() => {
socket.emit('join', uuid);
socket.emit('isActive', uuid);
return () => {
console.log('removed');
socket.off('newMsg');
}
}, []);
socket.on('newMsg', msg => {
console.log('debug');
let msgs = msgArr.map(msg => msg);
msgs.push({
type : 'received',
msg,
});
setMsgArr(msgs);
if(!open) setUnreadMsgs(unreadMsgs + 1);
chatBoxRef.current.scrollTop = chatBoxRef.current.scrollHeight;
});
当服务器在套接字上触发 newMsg 事件时,我希望它用新的 msg 更新 msgArr 状态,但我看到 console .log('debug') 语句运行的次数比预期的要多,而且事情并没有像我预期的那样工作。我的意思是,它应该只对一次。但它没有,它运行多次,在某些时候,“次”甚至达到 40。作为新的反应,我不明白为什么会发生这种情况。因此,如果有人能对这个问题有所了解,我将不胜感激,这让我好几天没睡了。我需要帮助。有人吗?
【问题讨论】:
标签: javascript node.js reactjs socket.io