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

React Big Calendar报错:Uncaught TypeError,切换视图崩溃求助

React Big Calendar 日期类型错误修复方案

问题根源

把事件存入localStorage时,JSON.stringify会自动将Date对象转为ISO格式字符串。取出后直接赋值给allEvents,导致事件的start和end是字符串类型,而React Big Calendar(RBC)需要的是Date对象。切换视图时RBC会调用Date对象的getXXX方法(比如getHours、getMonth),字符串没有这些方法,所以抛出TypeError: d[("get" + method)] is not a function。

修复步骤

1. 解析localStorage数据时转换日期类型

修改obtenerDatos函数,把每个事件的start和end重新转为Date对象:

const obtenerDatos = () => {
  const items = JSON.parse(localStorage.getItem(`${turno}`));
  if (items) {
    // 遍历事件,将日期字符串转回Date对象
    const parsedEvents = items.map(event => ({
      ...event,
      start: new Date(event.start),
      end: new Date(event.end)
    }));
    setAllEvents(parsedEvents);
  } 
}

2. 优化useCallback依赖(可选但推荐)

handleSelectSlot里用了函数式更新setAllEvents(prev => ...),不需要依赖allEvents,可以把依赖数组改为空,避免不必要的回调重建:

const handleSelectSlot = useCallback(
  ({ start, end }) => {
    const id = uuidv4();
    const title = window.prompt("Turno:");
    if (title) {
      setAllEvents((prev) => [...prev,{ 
        start: new Date(start), // start本身是Date对象,无需Date.parse
        end: new Date(end), 
        title, 
        id 
      }]);
    }
  },
  [] // 移除allEvents依赖
);

额外提示

  • 你的locales配置里写的是"es-US"但引用的是en-US locale,如果需要西班牙语日历,要改为require("date-fns/locale/es")并将键改为"es-ES"。
  • 保存数据时无需额外处理,JSON.stringify会自动将Date转为字符串,只要取出时转换回去即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:50:31