[英]Reactjs Asynchronously load events from calendar - Google Calendar API
我正在嘗試從我使用 gapi.client.request 獲取的谷歌日歷 api 加載事件,問題是我無法找到如何正確使用 async/await 的方法。 我的事件在我的演示組件之后加載。 我之前使用過 async await,它可以與 fetch 和其他 API 一起正常工作。 還有其他方法可以等待 google.thenable object。 因為它是 promise,所以我認為它會更容易處理,就像我之前使用 fetch 處理承諾一樣。 我在這里完全迷失了,任何幫助將不勝感激。
const [events, setEvents] = useState([]);
useEffect(() => {
getEvents();
});
async function get(){
await getEvents();
}
function getEvents(){
init()
.then(() => {
return gapi.client.request({
'path': `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
})
})
.then((res) => {
const allEvents = res.result.items;
setEvents(sortedEvents);
}, (reason) => {
console.log(reason);
});
}
事件不會在組件之前加載,因此它們沒有被正確等待。 我希望我的事件異步加載,以便它們與其他演示組件同時顯示。
您的代碼中似乎存在一些小問題。
首先,不要忘記讓你的getEvents()
function 異步。
其次,請記住在您的useEffect()
方法中添加第二個參數,以阻止 function 在每次更新時觸發。
因此,您的代碼應如下所示:
const [events, setEvents] = useState([]);
useEffect(() => {
getEvents();
}, []);
async function get(){
await getEvents();
}
async function getEvents(){
init()
.then(() => {
return gapi.client.request({
'path': `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
})
})
.then((res) => {
const allEvents = res.result.items;
setEvents(sortedEvents);
}, (reason) => {
console.log(reason);
});
}
您可能想閱讀更多關於如何使用 React 處理 API 的信息,這里是一個很好的資源。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.