首页 > 解决方案 > firebase 新手,不确定为什么“createdAt”字段未在 Chat 组件中呈现

问题描述

我正在尝试使用 react 和 firebase 制作一个网络聊天应用程序。我是后者的新手,我不知道为什么,当我将具有属性 text、photoURL、displayName、uid 和 createdAt 的文档添加到消息集合时,通过映射时最后一个属性不会显示在 Chat 组件中每个文件。

聊天.jsx

import React, { useState, useEffect, useRef } from 'react';
import Logout from './Logout';
import { auth, store } from '../firebase';
import SendMsg from './SendMsg';

const Chat = () => {
    const scroll = useRef()
    const [messages, setMessages] = useState([]);
    useEffect(() => {
        store.collection("messages").orderBy("createdAt").limit(100).onSnapshot(snapshot => {
            setMessages(snapshot.docs.map(doc => doc.data()));
        })
    },[]) // no need to add messages to the second argument because onSnapshot takes care of running useEffect according to collections only
    return (
        <div>
            <Logout /> 
            <div className = "messages">
            {messages.map(({id, text, photoURL,displayName, uid, createdAt}) =>
                // unique id for each document 
                <div>
                    <div key = {id} className = {`message ${uid === auth.currentUser.uid ? "sent" : "received"}`}> 
                    {console.log(id)}
                    <img src={photoURL} alt=""/>
                    <div className="displayName">{displayName}</div>
                    <p>{createdAt}</p>
                    <p>{text}</p>
                    </div>
                </div>
            )}
            </div>
            <SendMsg scroll={scroll} />
            <div ref={scroll}></div>
        </div>
    );
}

export default Chat;

发送消息.jsx

import React, {useState} from 'react';
import { Button, Input } from '@material-ui/core';
import firebase from 'firebase';
import {store, auth} from "../firebase"

const SendMsg = ({scroll}) => {
const [message, setMessage] = useState(" ");

async function sendMessage(e){
    e.preventDefault(); //prevents the send button from refreshing the page
    const {uid, photoURL, displayName}  = auth.currentUser //information about the current user
    await store.collection("messages").add({
        text: message,
        photoURL,
        displayName,
        uid,
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
    })
    setMessage('') //empty input
    scroll.current.scrollIntoView({ behavior: "smooth" })
}
return (
    <div className = "sendMessage">
        <form onSubmit = {sendMessage}>
            <Input style={{ width: '78%', fontSize: '15px', fontWeight: '550', marginLeft: '5px', marginBottom: '-3px' }} value = {message} onChange = {(e) => setMessage(e.target.value)} placeholder = "Type Here!" />
            <Button style={{ width: '18%', fontSize: '20px', fontWeight: '600', margin: '4px 5% -13px 5%', maxWidth: '200px'}} type="submit">Send</Button>
        </form>
    </div>
);
}

export default SendMsg;

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


我也有点新,但我用它来存储创建日期:

firebase.firestore.Timestamp.fromDate(new Date()),

您还需要在显示时对其进行转换

date.toDate().toDateString();

编辑 1:记得取消订阅你的 onSnapshot 监听器:

useEffect(() => {
        return store.collection("messages").orderBy("createdAt").limit(100).onSnapshot(snapshot => {
            setMessages(snapshot.docs.map(doc => doc.data()));
        })
    },[])

推荐阅读