我有一个React的聊天程序,但我不知道如何实现消息的已读状态。
后端:
socket.on("read_message", async({message_id})=>{
const updated_message = await Message.findByIdAndUpdate(message_id, {is_read: true}, {new: true});
if(updated_message){
socket.emit("road_message", {
status: 'success'
})
}
})
messageContainer
组件(前):
const MessageContainer = ({ messages }) => {
const messageRef = useRef(null);
useEffect(() => {
const domNode = messageRef.current;
if (domNode) {
domNode.scrollTop = domNode.scrollHeight;
}
}, [messages.length]);
return (
<div
id="messages"
className="scroll-smooth flex flex-col h-full space-y-4 p-3 overflow-y-auto scrollbar-thumb-blue scrollbar-thumb-rounded scrollbar-track-purple scrollbar-thin scrolling-touch"
ref={messageRef}
>
{messages.length > 0 ? (
<>
{messages.map((message, index) => (
<Message message={message} key={index} />
))}
</>
) : (
<NoMessage />
)}
</div>
);
};
export default MessageContainer;
消息组件:
const Message = ({ message }) => {
const isMe = window.localStorage.getItem('user_id') === message.from;
useEffect(()=>{
const readMessage = ()=>{
if (!isMe && message.is_read === false) {
socket.emit('read_message', {
message_id: message._id,
});
}
}
readMessage();
socket.on("road_message", ({status})=>{
if(status === 'success') {}
})
},[isMe, message])
return isMe ? (
<OutcomingMessage message={message} />
) : (
<IncomingMessage message={message} />
);
};
export default React.memo(Message);
我不知道如何实施它。请帮帮我!
1条答案
按热度按时间ru9i0ody1#
首先,您在
Message
组件中有一个错字。socket.on("road_message"
应该是socket.on("read_message"
。然后,要在UI上显示读取状态,您可以设置一个状态,例如在
Message
中称为isRead
,并将其传递给OutcomingMessage
:和
OutcomingMessage
,抓取该布尔值以相应地显示一个指标,类似于: