date-fns formatRelative RangeError:使用基本的新 Date() js 函数时时间值无效



我正在 react 中制作一个待办事项列表应用程序,并希望使用 formatRelative 作为创建日期。创建待办事项后,我将新的 Date(( 设置为变量,然后将该日期设置为 todo.created。然后,它以应用的状态存储,随后发送到 Firebase 服务器进行存储。但是,当我重新加载页面时,我收到 RangeError:待办事项列表尝试呈现时的时间值无效。

下面是一些代码:

// 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

谢谢你@RobG。一旦你们帮助我意识到问题是如何从 Firebase 接收对象的,我就能够解决问题。我能够通过简单地使用 toDate(( 函数来解决问题:

// 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 });
}
});
}

最新更新