提问者:小点点

将日期保存到本地存储


我正在构建一个带有同步待办事项列表的日历。我试图根据用户输入将特定日期保存到本地存储。此时,待办事项被保存到本地存储,并显示在带有文本和日历的待办事项列表中,但如果刷新页面,日历中的待办事项将消失。

在本地存储中,它的写入值:[object HTMLInputElement]

function saveTodosToLS() {
 const todosAsString = JSON.stringify(todos);
 localStorage.setItem("todos", todosAsString);
}

function loadTodos() {
 const todosAsString = localStorage.getItem('todos');
 todos = JSON.parse(todosAsString || '[]');
}

这是我正在努力解决的问题

function saveCalendarToLS() {
  const todoDateAsString = Date.parse('dateOfTodos');
  todoDateAsString = JSON.stringify(dateOfTodos);
  localStorage.setItem('dateOfTodos', todoDateAsString);
}

function loadTodosInLS() {
  const todoDateAsString = localStorage.getItem('dateOfTodos');
  dateOfTodos = Date.parse(todoDateAsString || '[]');
}


共1个答案

匿名用户

  • 您不应该使用全局(或者任何类型的共享状态)来传递数据。当数据通过函数参数传入并通过返回值返回时,程序更容易理解

我会这样做:

(请参见代码下方我的注释项目列表)

const LOCALSTORAGE_KEY_TODOS = "todos";

function saveTodos( todosArray ) {
    if( !Array.isArray( todosArray ) ) throw new Error( "Expected 'todosArray' to be an array but encountered " + ( typeof todosArray ) ); // Defensive programing!

    const todosAsJson = JSON.stringify( todosArray );

    window.localStorage.setItem( KEY_TODOS, todosAsJson );
}

/** Returns an array of todo objects. Returns an empty array if nothing is saved in the store. */
function loadTodos() {
    
    const todosAsJson = window.localStorage.getItem( KEY_TODOS );
    if( todosAsJson ) {
        try {
            const todos = JSON.parse( todosAsJson );
            if( Array.isArray( todos ) ) return todos;
        }
        catch( err ) {
            console.error( "Couldn't load TODOs: %o", err );
        }
    }

    return [];
}

function saveCalendar( date, todos ) {
    if( !isDate( date ) ) throw new Error( "Expected 'date' to be a Date object." );
    if( !Array.isArray( todosArray ) ) throw new Error( "Expected 'todosArray' to be an array but encountered " + ( typeof todosArray ) );
    
    const dateKey = 'CALENDAR_' + getDateOnlyString( date );

    const todosAsJson = JSON.stringify( todosArray );
    window.localStorage.setItem( dateKey, todosAsJson );
}

/** Returns an array of todo objects. Returns an empty array if nothing is saved in the store for that date. The time component of 'date' is ignored. */
function loadCalendar( date ) {

    if( !isDate( date ) ) throw new Error( "Expected 'date' to be a Date object." );

    const dateKey = 'CALENDAR_' + getDateOnlyString( date );

    //

    const todosAsJson = window.localStorage.getItem( dateKey );
    if( todosAsJson ) {
        try {
            const todos = JSON.parse( todosAsJson );
            if( Array.isArray( todos ) ) return todos;
        }
        catch( err ) {
            console.error( "Couldn't load TODOs: %o", err );
        }
    }

    return [];
}

/** Returns boolean true or false */
function isDate( value ) {
    // https://stackoverflow.com/questions/643782/how-to-check-whether-an-object-is-a-date

    return value instanceof Date && ( typeof value.getMonth === 'function' );
}

/** Returns `date` formatted as ISO 8601 yyyy-MM-dd */
function getDateOnlyString( date ) {
    // HACK: https://stackoverflow.com/questions/25159330/how-to-convert-an-iso-date-to-the-date-format-yyyy-mm-dd
    return date.toISOString().substring(0,10); // "if it works..."
}
  • 避免发明自己的首字母缩略词:我看到您正在使用“LS”这是localStorage的缩写,但是这在JavaScript社区中不是一个常见的缩写,因此我会避免使用它,只需将其称为:localStorage