You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键说明

  1. 首次加载时,localStorage.fullCalendarDefaultDate为null,三元表达式会返回new Date()(当前日期),避免无效日期对象报错
  2. 用户切换视图后,datesSet回调会把当前视图的起始日期存入localStorage,下次刷新页面时自动加载该日期
  3. 无需额外提前设置localStorage,三元判断已经处理了首次加载的默认情况

内容的提问来源于stack exchange,提问作者macca4244

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:10:04