[英]React batch updates for multiple setState() calls inside useEffect hook
[英]Implementing multiple Firestore calls at different times within useEffect React hook
useEffect(async() => {
await getWord();
const interval = setInterval(() =>{
time2 = time2 - 1;
if (time2 == 0) {
clearInterval(interval);
let dataURL = canvasRef.current.toDataURL();
const db = firebase.firestore();
db.collection("rooms").where("code", "==", code).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("rounds").where("round", "==", round).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("pictures").add({artist: name, dataURL: dataURL, votes: 0}).then(() => {
setVoteTime2(true);
});
});
});
});
});
}
}, 1000);
}, []);
上面的 useEffect 鈎子出現錯誤。 getWord是一個實現 Firestore 調用的 function。 錯誤是:“TypeError:n 不是函數”,它涉及 getWord 中發生的 firestore function以及 time2 == 0 時發生的 firestore 調用。我怎樣才能讓兩個異步調用都發生,顯然是 firestore當 time2 == 0 時發生在getWord內部的調用發生在調用之前? 如果需要更多信息,請告訴我。 我只是不明白使用 await 不能解決這個問題。
您不能將異步 function 作為回調傳遞給 useEffect 掛鈎,因為它返回 Promise 這是不允許的。 只需嘗試在 useEffect 中調用您的 function (但不要將回調 function 定義為異步本身),然后在 function 內部執行您的異步任務...
useEffect(() => {
// call your function
myAsyncFunc(); <--- Here
async function myAsyncFunc () => {
await getWord();
const interval = setInterval(() =>{
time2 = time2 - 1;
if (time2 == 0) {
clearInterval(interval);
let dataURL = canvasRef.current.toDataURL();
const db = firebase.firestore();
db.collection("rooms").where("code", "==", code).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("rounds").where("round", "==", round).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("pictures").add({artist: name, dataURL: dataURL, votes: 0}).then(() => {
setVoteTime2(true);
});
});
});
});
});
}
}, 1000);
}
}, []);
它的作用是使您免於返回 Promise 但仍允許您執行所有異步任務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.