FullCalendar首次加载时localStorage失效问题求助
解决FullCalendar首次加载日期记忆报错问题
问题核心是首次加载时localStorage.fullCalendarDefaultDate不存在(值为null),直接传给new Date()会生成无效日期对象,导致FullCalendar调用其方法时抛出Cannot read properties of null (reading 'getUTCFullYear')错误。你之前加的判断逻辑错误,因为initialDate是配置项中的变量,此时还未定义,判断不生效反而会强制覆盖localStorage值为当前日期。
正确修改方案
在设置initialDate时,先校验localStorage中的值是否有效,无效则使用当前日期:
var calendar = new FullCalendar.Calendar(calendarEl, { timeZone: 'UTC', locale:'en', headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,dayGridWeek,dayGridDay', //right: 'dayGridMonth,timeGridWeek,timeGridDay' Includes time views when we add them }, // 先判断localStorage值是否存在,不存在则用当前日期 initialDate: localStorage.fullCalendarDefaultDate ? new Date(localStorage.fullCalendarDefaultDate) : new Date(), events: 'loadMasterDates.php', editable:true, datesSet: function(dateInfo) { var date = new Date(dateInfo.view.currentStart); localStorage.fullCalendarDefaultDate = date.toISOString(); } })
关键说明
- 首次加载时,
localStorage.fullCalendarDefaultDate为null,三元表达式会返回new Date()(当前日期),避免无效日期对象报错 - 用户切换视图后,
datesSet回调会把当前视图的起始日期存入localStorage,下次刷新页面时自动加载该日期 - 无需额外提前设置localStorage,三元判断已经处理了首次加载的默认情况
内容的提问来源于stack exchange,提问作者macca4244
相关产品推荐
相关产品推荐

