首页 > 解决方案 > 如何显示从firestore检索到的时间戳类型元素

问题描述

我想显示使用 Firestore 创建的集合的内容,我有一个字段“日期”,它的类型为时间戳

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

错误:对象作为 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;

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


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

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

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

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

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


推荐阅读