reactjs - 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;
解决方案
我也有点新,但我用它来存储创建日期:
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()));
})
},[])
推荐阅读
- python-3.x - 有效地创建具有空值的分类数据框
- css - 在屏幕的不同位置放置不同的 Materialise toast [版本:1.0.0]
- sql-server - HIbernate 工具 org.hibernate.exception.JDBCConnectionException:调用 Driver#connect 时出错
- javascript - 如何创建可以从 Python 调用的 JavaScript API?
- c# - MVVM 结构:在 MVVM 中将文件发送到服务器的位置在哪里?
- haskell - 双函子与箭头方法
- bash - 如果第一列匹配,则处理第二列
- javascript - 如何对 keydown 和 click 事件使用相同的功能?
- macos - 移植一个Window专用工具到macOS,这个工具可以修改其他应用程序的属性
- python - 无法在 django 应用程序上显示外键属性