【问题标题】:how to display a timestamps type element retrieved from firestore如何显示从firestore检索到的时间戳类型元素
【发布时间】:2020-08-13 20:13:02
【问题描述】:

我想显示我使用 Firestore 创建的集合的内容,我有一个类型为 timestamp

的字段“日期”

当我想显示值时,我得到一个错误:

错误:对象作为 React 子对象无效(找到:对象与键 {seconds, nanoseconds})。如果您打算渲染一组子项,请改用数组。

我在@material-ui 的表格中显示我收藏的内容。

index.js

import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import { FirebaseContext } from '../Firebase'



const Welcome = () => {

    const firebase = useContext(FirebaseContext);
    const [nameColl, setNameColl] = React.useState([]);
   
      React.useEffect(() => {
        const fetchData = async () => {
          const db = firebase.db;
          const data = await db.collection("nameColl").get();
          setNameColl(data.docs.map(doc => ({ ...doc.data(), id: doc.id })));
        };
        fetchData();
      }, []);

      return(
                <TableContainer component={Paper}>
                    <Table aria-label="simple table">
                        <TableHead>
                        <TableRow>
                            <TableCell align="right"> Date&nbsp;</TableCell>
                        </TableRow>
                        </TableHead>
                        <TableBody>
                        {nameColl.map(nameColl => (
                            <TableRow key={nameColl.id}>
                            <TableCell align="right"> {nameColl.date} </TableCell> 
                            </TableRow>
                        ))}
                        </TableBody>
                    </Table>
                    </TableContainer>
          )

firebase.js

import app from 'firebase/app';
import 'firebase/firestore'

const config = {...};


class Firebase{

    constructor(){
        app.initializeApp(config)
        this.db = app.firestore();
    }
   
}

export default Firebase;

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    当您向视图提供 Firestore 时间戳对象时,您必须弄清楚您实际想要显示的内容。我认为这个问题是在渲染时发生的:

    <TableCell align="right"> {nameColl.date} </TableCell> 
    

    错误消息提示您不能在此处提供对象。您可能需要某种字符串格式。 Timestamp 对象不会为您自己格式化(它不知道您真正想要什么)。但是您可以将时间戳转换为日期,然后将其转换为默认字符串格式:

    <TableCell align="right"> {nameColl.date.toDate().toString()} </TableCell> 
    

    但是,如果这对您不起作用,您最终仍会弄清楚您真正想要显示的内容。

    【讨论】:

    • 您好,感谢您的帮助,这是我丢失的toString()。我使用 new Intl.DateTimeFormat(...).format(name.Coll).toString()
    猜你喜欢
    • 2020-07-28
    • 2020-04-04
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2012-05-07
    • 2012-09-23
    • 2020-12-22
    • 2023-01-23
    相关资源
    最近更新 更多