我正在将数据feching到firebase中,但当我重新加载页面时,页面停止呈现,

dojqjjoe  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(93)
function Chat() {
  const [input, setInput] = useState("");
  const [seed, setSeed] = useState("");
  const { roomId } = useParams();
  const [roomName, setRoomName] = useState("");
  const [messages, setMessages] = useState("");

  useEffect(() => {
    if (roomId) {
      db.collection("rooms")
        .doc(roomId)
        .onSnapshot((snapshot) => setRoomName(snapshot.data().name));

      db.collection("rooms")
        .doc(roomId)
        .collection("messages")
        .orderBy("timestamp", "asc")
        .onSnapshot((snapshot) =>
          setMessages(snapshot.docs.map((doc) => doc.data()))
        );
    }
  }, [roomId]);

  useEffect(() => {
    setSeed(Math.floor(Math.random() * 5000));
  }, [roomId]);

  const sendMessage = (e) => {
    e.preventDefault();
    console.log("you typed >>>", input);
    setInput("");
  };

  return (
    <div className="chat">
      <div className="chat__header">
        <Avatar
          alt="random"
          src={`https://avatars.dicebear.com/api/pixel-art/${seed}.svg`}
          sx={{ width: 38, height: 38 }}
        />
        <div className="chat__headerInfo">
          <h3>{roomName}</h3>
          <p>last seen at...</p>
        </div>
        <div className="chat__headerRight">
          <IconButton>
            <SearchIcon />
          </IconButton>
          <IconButton>
            <AttachFileIcon />
          </IconButton>
          <IconButton>
            <MoreVertIcon />
          </IconButton>
        </div>
      </div>
      <div className="chat__body">
        {messages.map((message) => (
          <p className={`chat__message ${true && "chat__reciever"}`}>
            <span className="chat__name">{message.name}</span>
            {message.message}
            <span className="chat__timestamp">
              {new Date(message.timestamp?.toDate()).toUTCString()}
            </span>
          </p>
        ))}
      </div>
      <div className="chat__footer">
        <InsertEmoticonIcon />
        <form>
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            type="text"
            placeholder="Type a message..."
          />
          <button onClick={sendMessage} type="submit">
            Send a message
          </button>
        </form>
        <MicIcon />
      </div>
    </div>
  );
}

export default Chat;

我试着修复像你说的那样放置isloading,但它更糟,也许我做错了,但它停止了渲染,没有数据传递到对象。
请注意,当我保存此代码{messages.map((message) => ( <p className={ chat__message ${true &&“chat__reciever”} }> <span className="chat__name">{message.name}</span> {message.message} <span className="chat__timestamp"> {new Date(message.timestamp?.toDate()).toUTCString()} </span> </p> ))}与localhost上它工作得很好,但当我重新加载页面并重新启动应用程序与保存的代码时,它不呈现

rekjcdws

rekjcdws1#

如果我将此语句const [messages, setMessages] = useState("");更改为const [messages, setMessages] = useState([]);,它将工作

相关问题