NodeJS 如何在React中更改消息的可见状态?

iaqfqrcu  于 2023-05-06  发布在  Node.js
关注(0)|答案(1)|浏览(144)

我有一个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);

我不知道如何实施它。请帮帮我!

ru9i0ody

ru9i0ody1#

首先,您在Message组件中有一个错字。socket.on("road_message"应该是socket.on("read_message"
然后,要在UI上显示读取状态,您可以设置一个状态,例如在Message中称为isRead,并将其传递给OutcomingMessage

import { useState, useEffect } from "react";

const Message = ({ message }) => {
  const isMe = window.localStorage.getItem("user_id") === message.from;
  const [isRead, setIsRead] = useState(false);
  useEffect(() => {
    const readMessage = () => {
      if (!isMe && message.is_read === false) {
        socket.emit("read_message", {
          message_id: message._id,
        });
      }
    };
    readMessage();
    socket.on("read_message", ({ status }) => {
      if (status === "success") {
        setIsRead(true);
      }
    });
  }, [isMe, message]);

  return isMe ? (
    <OutcomingMessage message={message} isRead={isRead} />
  ) : (
    <IncomingMessage message={message} />
  );
};

export default React.memo(Message);

OutcomingMessage,抓取该布尔值以相应地显示一个指标,类似于:

const OutcomingMessage = ({ message, isRead }) => {
  return (
    <>
      {message.is_read || isRead && <p>Message read</p>} <div>{message.whatever}</div>
    </>
  );
};

相关问题