0

index.js

 const messageContainer = document.querySelector('.msg');
const append = (message, position) => {
    console.log(message)
    const messageElement = document.createElement('div');
    messageElement.innerText = message;
    messageElement.classList.add('message');
    messageElement.classList.add(position);
    console.log(messageElement)
    messageContainer.append(messageElement);
    console.log(messageContainer)
};
const SERVER = "http://localhost:3010";
var socket = io(SERVER);
socket.on('receive_message', (message) => {
    console.log('Connected');
    console.log(message.content);
    setRMsg(message);
    console.log(rmsg)
    // append(`${message ? message.name : ''}: ${message ? message.content : ''}`, 'right');
    // // if (message.sendBy === 'user') {
        // append(`${message.content} `, 'left');
    // };
});
console.log(rmsg);
if (rmsg && rmsg != '') {
    append(`${rmsg.content} `, 'left');
    setRMsg('')
}
const send = () => {
    console.log('*95')
    console.log(sending)
    if (sending === '' || sending.senderChatID === '' || sending.content === '' || id === '') {
        console.log('***')
        toast.error('Missing Required Field', {
            position: "top-right",
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
        });
    }
    else {
        let obj = {
            senderChatID: sending.senderChatID,
            receiverChatID: id,
            content: sending.content,
            sendBy: sendVia,
            chatId: id,
            name: name ? name.name : '',
            profile_pic: name ? name.profile_pic : '',
            role: name ? name.role : '',
            createdAt: new Date(Date.now()),
            user_id: id
        };
        append(`${name ? name.name : ''}: ${sending.content}`, 'right');
        const input = document.getElementById('messageInp');
        input.value = '';
        socket.emit('send_message', obj);
}

'recieve_message' 事件被多次点击,但它必须点击一次,而点击按钮发送功能工作正常,但在接收消息时它被多次点击不知道为什么,因为我是 socket.io 的新手,可能是我在做小错误。任何帮助将不胜感激

4

1 回答 1

0

你可能在每次重新渲染你的React组件时重新注册。将代码放入一个带有数组的数组中,只需这样做一次:-socket.on(...)useEffect[]

const socketObj = useRef(io("http://localhost:3010"));
const socket = socketObj.current;

useEffect(()=>{
socket.on('receive_message', (message) => {
    console.log('Connected');
    console.log(message.content);
    setRMsg(message);
    console.log(rmsg)
    // append(`${message ? message.name : ''}: ${message ? message.content : ''}`, 'right');
    // // if (message.sendBy === 'user') {
        // append(`${message.content} `, 'left');
    // };
});
},[]);

在这里我一直使用它socketref因为我相信它一旦初始化并参与渲染流程就不会改变,但如果你需要,你甚至可以将它作为一个状态。

于 2021-03-09T14:25:24.463 回答