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

FullCalendar点击日期未切换至日视图,状态更新但未重渲染

解决FullCalendar点击日期切换日视图不更新的问题

问题出在你使用了initialView和initialDate这两个初始化属性,它们仅在组件首次挂载时生效,后续状态变化不会触发FullCalendar重新渲染。要动态切换视图和日期,需要通过FullCalendar的实例API来操作。

修改步骤:

  • 用useRef创建FullCalendar的引用,用于调用实例方法
  • 在handleDateClick中直接调用实例的changeView和gotoDate方法,替代修改state触发重新渲染的方式

修改后的代码:

import dayGridPlugin from "@fullcalendar/daygrid";
import FullCalendar from "@fullcalendar/react";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { useState, useEffect, useRef } from "react";

export default function Calendar(props) {
  const calendarRef = useRef(null);
  const [selectedDate, setSelectedDate] = useState(null);
  const [view, setView] = useState("dayGridMonth");

  const handleDateClick = (info) => {
    // 直接调用FullCalendar实例方法切换视图和日期
    if (calendarRef.current) {
      calendarRef.current.changeView("timeGridDay");
      calendarRef.current.gotoDate(info.dateStr);
    }
    setSelectedDate(info.dateStr);
    setView("timeGridDay");
  };

  useEffect(() => {
    console.log("Selected Date:", selectedDate);
    console.log("View:", view);
  }, [selectedDate, view]);

  return (
    <FullCalendar
      ref={calendarRef}
      plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
      initialView={view}
      selectable="true"
      selectOverlap="false"
      height="80vh"
      initialDate={selectedDate}
      themeSystem="standard"
      headerToolbar={{
        start: "today prev,next",
        center: "title",
        end: "dayGridMonth, timeGridWeek, timeGridDay",
      }}
      dateClick={handleDateClick}
    />
  );
}

关键说明:

  • initialView和initialDate仅负责组件初始化时的状态,后续动态修改必须依赖FullCalendar提供的实例方法
  • 通过useRef获取到FullCalendar实例后,可以调用官方文档中的所有实例方法,比如changeView切换视图、gotoDate跳转日期等
  • 保留state只是为了日志记录或其他业务需求,核心的视图切换逻辑由实例API完成

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:24:54