问题
I am not really sure what I am doing wrong here. Maybe it is a simple error. Any help would be appreciated. I get the following error in react.
The inital render is fine but the error occurs on the rerender with the new state.
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:
There is an issue with the selectable option and hooks. If you take out selectable it should work. Alternatively, you need to pass a reference to the calendar and unselect it before manipulating the state.
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 ... />
)
}
来源:https://stackoverflow.com/questions/61006669/react-fullcalendar-unable-to-add-new-event-to-the-calendar-after-updating-the-st