React FullCalendar 更新状态后无法向日历添加新事件

IT技术 reactjs fullcalendar fullcalendar-4
2021-05-07 06:23:03

我不确定我在这里做错了什么。也许这是一个简单的错误。任何帮助,将不胜感激。我在react中收到以下错误。

在此处输入图片说明

初始渲染很好,但在使用新状态重新渲染时发生错误。

import React, { useReducer, useRef, useState } from 'react';
import * as reducer from './reducers'
import * as actions from './actions'
import "@fullcalendar/core/main.css";
import "@fullcalendar/daygrid/main.css";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import timeGridPlugin from "@fullcalendar/timegrid";
//import events from '../Columns/events'
const _events = [
    { title: "event 1", start: "2020-04-01", end: "2020-04-03" },
    { title: "event 2", start: "2020-04-04", end: "2020-04-06" }
  ]
const Calendar = props => {
    //const [calendarEvents, dispatchEvents] = useReducer(reducer.events, _events)
    const [calendarEvents, setEvents] = useState(_events)

    const calendarRef = useRef()

    function confirmation(dateInfo) {
        console.log(`dateInfo:`, dateInfo);
        let answer = window.confirm("create event?")
        if(answer){
            const payload = { title: "event " + calendarEvents.length, start: "2020-04-07", end: "2020-04-09" }
            //dispatchEvents({type: actions.EVENT_ADD, payload})
            setEvents([...calendarEvents, payload])
            //calendarRef.current.props.events = [...calendarEvents, payload]
            console.log(calendarRef.current);
        }
    }
    debugger;
    return(
        <>
        <FullCalendar
        ref={calendarRef}
        defaultView="dayGridMonth"
        plugins={[dayGridPlugin, interactionPlugin, timeGridPlugin]}
        events={calendarEvents}
        editable
        eventResizableFromStart
        selectable
        //eventOverlap={false}
        dateClick={confirmation}
        eventBackgroundColor="#001532"
        eventColor="white"
        eventTextColor="white"
        header={{
            left: 'prev,next today',
            center: 'test title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
        }}
        eventClick={console.log}
      />
        </>
    )
}

export default Calendar

1个回答

可选选项和挂钩存在问题。如果你取出 selectable 它应该可以工作。或者,您需要传递对日历的引用在操作状态之前取消选择它

import React, {useRef, useState} from 'react'
...
export default function MyCalendar() {
    const CalendarRef = useRef()
    const [events, setEvents] = useState([])

    function handleUpdateState(){

        const calendarApi = CalendarRef.current.getApi()
        calendarApi.unselect()

        let newEvents = [...events, { insert new event object }]

        setEvents(newEvents)

    }

    return (
        <FullCalendar ... />
    )
}