我是 JavaScript 和 React 新手,我想制作一个小日历,从 API 检索事件并将其显示在日历中。整个 API 和数据恢复部分可以工作,但我无法在页面上显示事件,并且没有任何控制台错误
我创建了一个像这样的页面(我知道我的代码看起来像意大利面条代码,但我是 js 新手)
import {
IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
} from "@ionic/react";
import React, { useState, useEffect } from "react";
import "./Home.css";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
function convertirFormatDate(dateString: string) {
const dateTimeParts = dateString.split(" ");
const dateWithoutTimeZone =
dateTimeParts[0] + "T" + dateTimeParts[1].split("+")[0];
return dateWithoutTimeZone;
}
interface Event {
title: string;
start: string;
end: string;
}
interface EventData {
summary: string;
start: string;
end: string;
description?: string;
prof?: string;
location?: string;
uid?: string;
}
const Home: React.FC = () => {
const [events, setEvents] = useState<Event[]>([]);
useEffect(() => {
fetch("http://myapi/api/planning/getPlanningPerName/sample", {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((json) => {
const events: Event[] = json.map((eventData: EventData) => ({
title: eventData.summary,
start: convertirFormatDate(eventData.start),
end: convertirFormatDate(eventData.end),
}));
setEvents(events);
});
}, []);
events.map((event: Event) => {
console.log(event);
});
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Mycalendar</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<div id="main-content">
<FullCalendar
plugins={[dayGridPlugin]}
initialView="dayGridDay"
locale={"fr"}
titleFormat={{ month: "long", day: "numeric" }}
events={events}
/>
</div>
</IonContent>
</IonPage>
);
};
export default Home;
处理后我的事件变量是一个 json 列表,如下所示:
{
"title": "my title.",
"start": "2024-04-10T09:30:00",
"end": "2024-04-10T11:00:00"
}
如果您有解决方案,我将非常感激。 (我知道这可能是一个愚蠢的错误)
我终于解决了这个bug,完整的日历不喜欢我们在加载组件后注入事件,所以你必须在显示它们之前放一点“加载”
return (
<IonPage>
{events.length ? (<>
// Render the calendar only when events are available
<IonHeader>
<IonToolbar>
<IonTitle>EDT 4 RT</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<div id="main-content">
<FullCalendar
plugins={[dayGridPlugin]}
initialView="dayGridDay"
locale={"fr"}
titleFormat={{ month: "long", day: "numeric" }}
events={events}
/>
</div>
</IonContent></>
) : (
// Display a loading indicator or placeholder while events are fetched
<IonContent fullscreen>
<p>loading</p>
</IonContent>
)}
</IonPage>
);