我正在使用React / NodeJS / SocketIO开发一个应用程序,并且其中有一个聊天室, 我想我用套接字做错了,所以我寻求帮助,
我想: -1,获取所有存储在服务器中的消息 -2,无需重新加载屏幕即可实时查看所有新邮件
以下是组件代码的总结
// I create a hook "messages" with nothing in it, first
const [messages, setMessages] = useState(false);
useEffect(() => {
// I initialize the socket when the component is mounted
socket.open();
// I get, all messages already sent, from the server
try {
const dataMessages = await axios.get(
`http://localhost:5000/api/chat/messages`
);
console.log("messages ", dataMessages);
// I put all the messages in the hook "messages"
setMessages(dataMessages.data);
} catch (error) {
console.log(error);
}
// am I supposed to do something here with the socket "send message" ????
// I stop the socket when the component is unmounted
return () => {
socket.close();
};
});
function sendMessage(e) {
e.preventDefault();
socket.emit("send message", {data});
}
return (
<input type="submit" onClick={sendMessage} />
)
我的主要问题是我每秒钟都会在浏览器控制台中获得useEffect的日志,而我看不到自己发送的新消息