【发布时间】:2021-11-15 13:58:47
【问题描述】:
我正在尝试设计一个在反应中使用套接字的聊天应用程序。每当从后端触发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("");
}
};
不知何故,它只是在对话数组中添加了新消息,并删除了所有其他对话。有什么办法可以解决这个问题?
【问题讨论】: