我是 React 的初学者,我正在尝试使用 node 和 socket.io 来学习实时聊天室的教程。但我在发送消息时遇到问题。 当用户加入一个房间并且我向房间发送消息时useEffect()
没有运行。但是当我正常发送它时它工作正常。
我尝试过控制台日志记录 useEffect()
和 sendMessage()
函数。
Chat.js
import React, { useState, useEffect } from "react";
import queryString from 'query-string';
import io from 'socket.io-client';
let socket;
const Chat = ({ location }) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const ENDPOINT = 'localhost:5000';
useEffect(() => {
const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT);
setName(name);
setRoom(room);
socket.emit('join', { name, room }, () => {
});
},[ENDPOINT, location.search]);
useEffect(() => {
console.log("effect started")
socket.on('message', (message) => {
console.log("effect running")
setMessages([ ...messages, message]);
});
console.log("effect unmounted");
}, [messages]);
const sendMessage = (event) => {
event.preventDefault();
if (message) {
console.log("sending message");
socket.emit('sendMessage', message, () => setMessage(''));
}
console.log(message, messages);
}
return (
<div className="outerContainer">
<div className="container">
<input
value={message}
onChange={(event) => setMessage(event.target.value)}
onKeyPress={(event) => event.key === 'Enter' ? sendMessage(event) : null}
/>
</div>
</div>
);
};
export default Chat;
<块引用>
index.js
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const PORT = process.env.PORT || 5000;
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
},
});
io.on('connection', (socket) => {
socket.on('join', ({ name, room }, callback) => {
const { error, user} = addUser({ id: socket.id, name, room});
if (error) {
return callback(error);
}
socket.emit('message', { user: 'admin', text: `${user.name}, welcome to the room ${user.room}`});
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name}, has joined`});
socket.join( user, room);
callback();
});
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
console.log("send message: ", message);
console.log(user.room);
io.to(user.room).emit('message', { user: user.name, text: message});
console.log('emitted');
callback();
});
socket.on('disconnect', () => {
console.log('User had left!!!');
});
});
app.use(router);
server.listen(PORT, () => console.log(`Server has started ${PORT}`));