我使用fullcalendar来显示React应用程序中的所有事件。
理想情况下,prev
和next
事件处理程序应该重新呈现事件。
这是我的密码。
calender_slice.js
const slice = createSlice({
name: 'calendar',
initialState,
reducers: {
getEvents(state, action) {
const { timecards } = action.payload;
const timecard_events = timecards.map(timecard => {
return {
title: `${timecard.first_name} ${timecard.last_name}(${timecard.role})`,
start: timecard.clock_in,
end: timecard.clock_out,
color: '#'+Math.floor(Math.random()*16777215).toString(16)
}
})
state.events = [...timecard_events];
state.isLoading = false;
},
...
export const getEvents = (
start_date = moment().startOf('month').toString(),
end_date = moment().toString()
) => async (dispatch) => {
dispatch(slice.actions.setLoading(true));
const res = await axios.post(`${backend}/timecards`, {
start_date,
end_date
})
dispatch(slice.actions.getEvents({timecards: res.data.timecards}));
};
calendar_view.js
const CalendarView = () => {
const calendarRef = useRef(null);
const dispatch = useDispatch();
const { events, isModalOpen, selectedRange, isLoading } = useSelector((state) => state.calendar);
const handleDatePrev = async () => {
const calendarEl = calendarRef.current;
if (calendarEl) {
const start_date = moment(calendarEl.props.defaultDate).subtract(1, 'month').startOf('month').format();
const end_date = moment(calendarEl.props.defaultDate).subtract(1, 'month').endOf('month').format();
const calendarApi = calendarEl.getApi();
try {
await dispatch(getEvents(true, start_date, end_date));
} catch (err) {
console.error(err);
}
calendarApi.prev();
setDate(calendarApi.getDate());
}
};
return (<Container maxWidth={false}>
<Header onAddClick={handleAddClick} />
<Toolbar
date={date}
onDateNext={handleDateNext}
onDatePrev={handleDatePrev}
onDateToday={handleDateToday}
onViewChange={handleViewChange}
view={view}
/>
<Paper className={classes.calendar}>
<FullCalendar
allDayMaintainDuration
defaultDate={date}
defaultView={view}
eventResizableFromStart
eventResize={handleEventResize}
events={events}
header={false}
height={800}
ref={calendarRef}
rerenderDelay={10}
weekends
plugins={[
dayGridPlugin,
timeGridPlugin,
interactionPlugin,
listPlugin,
timelinePlugin
]}
/>
</Paper>
</Container>
)
}
此代码运行良好,每次都能正确地分派事件,但fullcalendar
不显示更新的事件数组。
我想知道当前约会的价值是多少。
这可能是因为状态的突变。在减速器中,应该返回一个新状态(而不是旧状态(。请参阅:https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#rules-减速器的将getEvents
更改为:
getEvents(state, action) {
const { timecards } = action.payload;
const timecard_events = timecards.map(timecard => {
return {
title: `${timecard.first_name} ${timecard.last_name}(${timecard.role})`,
start: timecard.clock_in,
end: timecard.clock_out,
color: '#'+Math.floor(Math.random()*16777215).toString(16)
}
})
return {
...state,
events: [...timecard_events],
isLoading: false,
}
},