【问题标题】:React: 'Maximum update depth exceeded' with FullCalendar反应:使用 FullCalendar '超出最大更新深度'
【发布时间】:2021-06-18 01:03:17
【问题描述】:

我正在使用 FullCalendar 进行反应,我正在努力应对状态....它返回此消息:

错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

我删除了代码中所有不必要的部分。

import React, { useState, useEffect } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";

const Top = () => {

  // Calendar info stored in state
  const [calendarEvents, setCalendarEvents] = useState([]);

  // method to retrieve dates
  const getEventsForThisMonth = () => {
    const events = [];
    events.push({
      title: "test",
      date: '2021-03-25',
    });
    return events;
  };

  useEffect(() => {
    const eventsCollected = getEventsForThisMonth();
    setCalendarEvents(eventsCollected);
  }, [calendarEvents]);

  return (
    <>
      <FullCalendar
        defaultView="dayGridMonth"
        plugins={[dayGridPlugin]}
        events={calendarEvents}
        locale="ja"
      />
    </>
  );
};

export default Top;

如果您希望我提供更多信息,请告诉我。 欢迎任何反馈/想法! 谢谢

【问题讨论】:

    标签: reactjs fullcalendar gatsby


    【解决方案1】:

    如前所述,您正在触发具有calendarEvents 依赖关系的useEffect,它再次设置日历事件(setCalendarEvents)的状态,这也再次触发useEffect,依此类推...创建一个无限循环。

    如果想避免它保留您的解决方法,您可能希望在第一时间设置事件,使用 useEffect 和空 deps ([]):

    import React, { useState, useEffect } from "react";
    import FullCalendar from "@fullcalendar/react";
    import dayGridPlugin from "@fullcalendar/daygrid";
    
    const Top = () => {
    
      // Calendar info stored in state
      const [calendarEvents, setCalendarEvents] = useState([]);
    
      // method to retrieve dates
      const getEventsForThisMonth = () => {
        const events = [];
        events.push({
          title: "test",
          date: '2021-03-25',
        });
        return events;
      };
    
    
      useEffect(()=>{
        const eventsCollected = getEventsForThisMonth();
        setCalendarEvents(eventsCollected);
      }, [])
    
      return (
        <>
          <FullCalendar
            defaultView="dayGridMonth"
            plugins={[dayGridPlugin]}
            events={calendarEvents}
            locale="ja"
          />
        </>
      );
    };
    
    export default Top;
    

    【讨论】:

      【解决方案2】:

      这是因为你 useEffect 在 useEffect 本身改变状态时,有 state 的依赖。
      当你的 useEffect 运行时 -> 它改变了状态 -> 改变的状态将触发 useEffect 运行 -> ...
      它会导致无限循环。
      要修复它,请根据您的需要更改 useEffect 的依赖关系。也许将 setCalendarEvents 放在 getEventsForThisMonth 函数中,并在 onChange 事件中使用此函数。

      【讨论】:

      • 感谢您的回复。这绝对是有道理的。但是我没有任何onchange,你能再检查一下代码吗?我只是将一组事件作为道具传递给我的组件。
      猜你喜欢
      • 1970-01-01
      • 2021-07-12
      • 2019-02-14
      • 2019-07-17
      • 1970-01-01
      • 2021-10-01
      • 2019-10-09
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多