[英]How to group messages in a chat instead of having each new message in a new section?
I'm building a chat system with React and socket.io, and I'm trying to achieve grouping messages together like Discord does it, or as seen in this screenshot .我正在使用 React 和 socket.io 构建一个聊天系统,并且我正在尝试像 Discord 那样将消息分组在一起,或者如此屏幕截图所示。 Basically, instead of creating a new section with your avatar again, it will just create a new message element and append it to your pre-existing section, unless the other user you're chatting with sends you a message or if it has been too long since your last message (in this case, 1 minute).基本上,它不会再次使用您的头像创建一个新部分,它只会创建一个新的消息元素并将其附加到您预先存在的部分,除非您正在与之聊天的其他用户向您发送了一条消息,或者它已经发送给您距离您的上一条消息已经很久了(在本例中为 1 分钟)。
Link to JSFiddle.链接到 JSFiddle。
The brown messages are my messages, and the black are the other users'.棕色消息是我的消息,黑色是其他用户的消息。
What I first thought was the correct solution was to group every message by 1 minute.我首先想到的正确解决方案是将每条消息按 1 分钟分组。
const sortByMinute = _.groupBy(messages, (msg) => {
return moment(msg.createdAt * 1000).startOf("minute").format();
});
However, the problem with doing this, as seen in the fiddle, is that it completely ignores when another users sends a message.然而,这样做的问题,正如在小提琴中看到的那样,当另一个用户发送消息时,它完全忽略了。 So when another user sends you a message, it still thinks it belongs in the same section, because it has no way to determine whether it comes from a new user or not, and frankly, I have no clue how to do it either.所以当另一个用户给你发送消息时,它仍然认为它属于同一部分,因为它无法确定它是否来自新用户,坦率地说,我也不知道如何去做。
How can I achieve this?我怎样才能做到这一点?
This is what I did: I divided the whole process in two steps:这就是我所做的:我将整个过程分为两步:
let lastMsg = lastMessages[lastMessages.length - 1]
if (lastMsg.user === m.user) {
lastMessages.push(m)
acc[acc.length - 1] = lastMessages
} else {
acc.push([m])
}
return acc;
}, [[firstMsg]])
const groups = newMessages.reduce((acc, m) => {
const message = m[m.length - 1]
acc[moment(message.createdAt * 1000).format()] = m
return acc
}, {})
Check the example: https://jsfiddle.net/Lw8gs6x7/检查示例: https : //jsfiddle.net/Lw8gs6x7/
Note: you'll need to refactor my code.注意:您需要重构我的代码。 It is not very clean.它不是很干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.