React 状态更改后 Fullcalendar 重新获取事件

Fullcalendar re-fetch events after change in React state

我有这个非常简单的 React 组件:

import { useState } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import { getCalendarEvents } from "../../utils/frontend/getEvents";
import EventModal from "../CreateEventModal";

const Calendar = ({ calendar: calendarId, eventColor }) => {
  const [isModalVisible, setModalVisibility] = useState(false);

  return (
    <>
      <button onClick={() => setModalVisibility(true)}>Open Modal</button>
      
      <FullCalendar
        plugins={[dayGridPlugin]}
        events={getCalendarEvents(calendarId)}      
      />

      <EventModal open={isModalVisible} onClose={() => setModalVisibility(false)} />
    </>
  );
}

export default Calendar;

然而,有一个问题。每当我打开模式时,Fullcalendar 决定重新获取我的事件。这里的代码 getCalendarEvents:

export const getCalendarEvents =
  (calendarId) => (info, successCallback, failureCallback) => {
    fetch(`/list-events?id=${calendarId}&timeMin=${info.start}&timeMax=${info.end}`)
      .then((res) => res.json())
      .then((res) => {
        if (res.success && res.data)
          successCallback(
            res?.data?.map((event) => ({
              id: event.id,
              title: event.summary,
              location: event.location,
              description: event.description,
              start: event.start?.dateTime,
              end: event.end?.dateTime,
            })) || []
          )
        else {
          failureCallback(new Error(res.error || "Something went wrong."));
        }
      })
  };

我认为这是 Fullcalendar 本身的问题。但是,有没有办法从我这边解决这个问题?

我正在使用 @fullcalendar/react 版本 5.10.1

我相信发生这种情况是因为每个渲染器都在处理“events={getCalendarEvents(calendarId)}”,这会创建对函数的新引用。

尝试这样的事情:

import { useState, useMemo } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import { getCalendarEvents } from "../../utils/frontend/getEvents";
import EventModal from "../CreateEventModal";

const Calendar = ({ calendar: calendarId, eventColor }) => {
  const [isModalVisible, setModalVisibility] = useState(false);
  
  const memoizedEventsFn = useMemo(() => {
    return getCalendarEvents(calendarId);
  }, [calendarId]);

  return (
    <>
      <button onClick={() => setModalVisibility(true)}>Open Modal</button>
      
      <FullCalendar
        plugins={[dayGridPlugin]}
        events={memoizedEventsFn}      
      />

      <EventModal open={isModalVisible} onClose={() => setModalVisibility(false)} />
    </>
  );
}

export default Calendar;

希望有用。如果没有,可以使用 memo 或 useMemo 来记忆 FullCalendar。