[英]date-fns formatRelative RangeError: Invalid time value when using basic new Date() js function
I'm making a todo list app in react, and want to use formatRelative for the date created.我正在制作一个待办事项列表应用程序,并希望使用 formatRelative 作为创建日期。 When the todo is created, I set a new Date() to a variable, and then set that date as todo.created.
创建 todo 时,我将 new Date() 设置为变量,然后将该日期设置为 todo.created。 It is then stored in the App's state and subsequently sent to a firebase server for storage.
然后将其存储在 App 的 state 中,随后发送到 firebase 服务器进行存储。 However, when I reload the page, I get the RangeError: Invalid time value for when the todo list tries to render.
但是,当我重新加载页面时,我得到 RangeError: Invalid time value for when the todo list try to render。
Here is some code:这是一些代码:
// creating the todo:
submitHandler = () => {
const today = new Date();
this.props.addTodo({
id: this.props.nextId(),
title: document.querySelector(".modal-title-input").value,
description: document.querySelector(".modal-desc-input").value,
due: document.querySelector(".modal-due-date-input").value,
priority: document.querySelector(".modal-priority-input").value,
created: today,
done: false,
});
// when the todo is rendered:
const todo = this.props.todo;
const today = new Date();
console.log(isValid(today, todo.created)) // true, true
console.log(formatRelative(today, todo.created)); // RangeError
Thank you @RobG.谢谢@RobG。 I was able to fix the issue once you guys helped me realize the problem was how the object was being received back from Firebase.
一旦你们帮助我意识到问题是如何从 Firebase 收到 object,我就能解决这个问题。 I was able to fix the problem by simply using the toDate() function:
我可以通过简单地使用 toDate() function 来解决这个问题:
// declared before the class
const fireLibrary = db.collection("todos").doc("library");
// inside the class
componentDidMount() {
fireLibrary.get().then((doc) => {
if (doc.exists && doc.data().todosLibrary) {
const lib = doc.data().todosLibrary.map(item => {
item.created = item.created.toDate()
return item
})
this.setState({ todosLibrary: lib });
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.