在React中渲染Firestore时间戳 [英] Rendering a firestore timestamp in react

查看:80
本文介绍了在React中渲染Firestore时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月来,我一直在努力弄清楚如何在响应中显示Firestore时间戳.

I have been trying for months to figure out how to display a firestore timestamp in react.

2019年12月,我在此帖子上接受的解决方案奏效.它不再起作用.我又回到了困境.

In December 2019, the solution I accepted on this post worked. It no longer works. I'm back to stuck.

我有一个firebase.js助手来记录日期:

I have a firebase.js helper to record dates with:

class Firebase {
  constructor() {
    app.initializeApp(config)
    this.firestore = app.firestore();
    this.auth = app.auth();
    this.serverTimestamp = app.firestore.FieldValue.serverTimestamp;


  }

我在表格中使用该帮助程序来记录条目的创建日期,如下所示:

I use that helper in forms to record the date an entry is created like so:

  await Firebase.firestore.collection("blog").doc().set({ 
    title: values.title,    
    createdAt: Firebase.serverTimestamp()

这样可以正确地将日期保存到Firestore文档中,如下所示:

That correctly saves a date into the firestore document that looks like this:

当我将鼠标悬停在日期上时,它会显示时间戳".我能够通过参考createdAt date来排序从Firestore返回的数据-因此很好奇时间戳可以用于对文档进行排序,但不能用于在屏幕上打印日期.

When I hover over the date, it shows 'timestamp'. I am able to order the data returned from firestore by reference to the createdAt date - so it's curious that the timestamp can be used to sort the documents but cannot be used to print the date on the screen.

当涉及到输出日期时,我又回到了上一篇文章中报告的所有相同错误-但是12月份有效的解决方案不再起作用.我在Firebase Slack频道中看到过这样的讨论,即最新版本的Firebase产生了一些意想不到的后果-有什么方法可以检查是否其中之一是时间戳破损的吗?

When it then comes to outputting the date, I am back to getting all the same errors I reported in the previous post - but the solution that worked in December, no longer works. I have seen a discussion in the firebase slack channel that a recent release of firebase has had some unintended consequences - is there any way to check if broken timestamps is one of them?

当我尝试时:

   {currentPost.createdAt.toDate().toISOString()}

TypeError:无法读取未定义的属性"toDate"

TypeError: Cannot read property 'toDate' of undefined

当我尝试时:

   {currentPost.createdAt.toDate()}

TypeError:无法读取未定义的属性"toDate"

TypeError: Cannot read property 'toDate' of undefined

当我尝试时:

   {new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")}

TypeError:无法读取未定义的属性秒"

TypeError: Cannot read property 'seconds' of undefined

当我尝试时(我知道这是行不通的,只是尝试寻找可能有助于解决此问题的见解):

When I try (I know this won't work but just trying to find insights that might help solve this problem):

   {currentPost.createdAt}

错误:对象作为React子对象无效(找到:带有键的对象 {seconds,nanoseconds}).如果您打算呈现一个 孩子,请改用数组.

Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead.

我已经看到一些帖子表示日期是不确定的,因为在firebase上的调用尚未返回值,但是当我console.log记录整个currentPost时,我得到了创建的At的值,即:

I have seen some posts which say the date is undefined because the call on firebase hasn't returned a value yet, but when I console.log the whole currentPost, I get a value for created At, which is:

createdAt:t秒:1586495818纳秒:888000000

createdAt: t seconds: 1586495818 nanoseconds: 888000000

看起来可疑的部分是"t".它代表我为了访问时间戳而应该做的事情吗?有谁知道如何调查"t"代表什么?

The part of this that looks suspicious is the "t". Does it represent something that I'm supposed to do something with in order to access the timestamp? Does anyone know how to investigate what the 't' represents?

我看过这篇文章,并请注意,每个答案都表明.toDate()扩展名应有助于将Firestore时间戳转换为可以输出的时间戳.这些解决方案都不能在这里使用.

I have seen this post and this post, and note that each of the answers to it suggest that the .toDate() extension should help to convert a firestore timestamp to something that can be output. None of those solutions work here.

有没有人找到一种当前的解决方案,可以同时保存和输出Firestore中的日期?

Has anyone figured out a current solution that allows to both save and output a date from firestore?

推荐答案

奇怪-我不知道为什么或如何工作,但确实可以.

Strange - I don't understand why or how this works, but it does.

我将useEffect更改为异步-如下.

I changed the useEffect to be async - as follows.

function ReadBlogPost () {
    const [loading, setLoading] = useState(true);
    const [currentPost, setCurrentPost] = useState({});
    let { slug } = useParams();


    useEffect(() => {

        const fetchData = async() => {

            try {

                const response = await Firebase.firestore
                    .collection("blog")
                    .doc(slug)
                    .get();

                console.log('response', response);

                let data = { title: 'not found' };

                if (response.exists) {
                    data = response.data();
                }

                setCurrentPost(data);
                setLoading(false);

            } catch(err) {
                console.error(err);
            }

        };

        fetchData();

    }, []);

然后在渲染中,我可以使用:

Then in the render, I can use:

 {!loading && new Date(currentPost.createdAt.seconds * 1000).toLocaleDateString("en-US")}

手指越过了这个作品几个月了.

Fingers crossed this works for more than a few months.

这篇关于在React中渲染Firestore时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆