使用 socket.io 时未添加消息
messages not getting added when using socket.io
我正在尝试使用反应中的套接字设计一个聊天应用程序。每当从后端触发 new_message
事件时,我都会尝试将该消息附加到现有消息数组中,但似乎无法正常工作。
这是我试过的代码:
useEffect(() => {
socket.on("new_message", (data) => { // receving the event and appending the new message in the existing array of messages.
setConversation([...conversation, data.message]);
});
});
useEffect(() => {
socket.emit("join_room", lead._id);
if (lead._id !== undefined) {
getConversationByRoomId(lead._id).then(({ data }) =>
setConversation(data.conversation)
);
}
}, [lead]);
const handleKeyPress = async (e) => {
if (e.key === "Enter") {
await postMessage(lead._id, { messageText: message }); // API which will save this message in the database and triggers an event called new_message to the socket
setMessage("");
}
};
不知何故,它只是在对话数组中添加了新消息,并删除了所有其他对话。可以做些什么来解决这个问题?
根据您在问题中提供的信息,我认为首先要改变和观察的是 socket.on
的实施方式。我不会在每次发生状态更新时都绑定一个新的事件处理程序,而且如果不删除清理函数中的前一个事件处理程序也是如此。
尝试利用 状态更新器 功能按以下方式进行操作:-
useEffect(() => {
socket.on("new_message", (data) => {
setConversation(prevConversation=>[...prevConversation, data.message]);
});
},[]);
还要确保 getConversationByRoomId
实际上返回了整个 conversation
数组,方法是在设置相同的状态之前记录它的值。
我正在尝试使用反应中的套接字设计一个聊天应用程序。每当从后端触发 new_message
事件时,我都会尝试将该消息附加到现有消息数组中,但似乎无法正常工作。
这是我试过的代码:
useEffect(() => {
socket.on("new_message", (data) => { // receving the event and appending the new message in the existing array of messages.
setConversation([...conversation, data.message]);
});
});
useEffect(() => {
socket.emit("join_room", lead._id);
if (lead._id !== undefined) {
getConversationByRoomId(lead._id).then(({ data }) =>
setConversation(data.conversation)
);
}
}, [lead]);
const handleKeyPress = async (e) => {
if (e.key === "Enter") {
await postMessage(lead._id, { messageText: message }); // API which will save this message in the database and triggers an event called new_message to the socket
setMessage("");
}
};
不知何故,它只是在对话数组中添加了新消息,并删除了所有其他对话。可以做些什么来解决这个问题?
根据您在问题中提供的信息,我认为首先要改变和观察的是 socket.on
的实施方式。我不会在每次发生状态更新时都绑定一个新的事件处理程序,而且如果不删除清理函数中的前一个事件处理程序也是如此。
尝试利用 状态更新器 功能按以下方式进行操作:-
useEffect(() => {
socket.on("new_message", (data) => {
setConversation(prevConversation=>[...prevConversation, data.message]);
});
},[]);
还要确保 getConversationByRoomId
实际上返回了整个 conversation
数组,方法是在设置相同的状态之前记录它的值。