首页 > 解决方案 > 在 useEffect React hook 中在不同时间实现多个 Firestore 调用

问题描述

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 调用的函数。错误是:“TypeError:n 不是函数”,它涉及发生在getWord中的 firestore 函数,以及在 time2 == 0 时发生的 firestore 调用。我怎样才能让两个异步调用都发生,显然是 firestore当 time2 == 0 时发生在getWord内部的调用发生在调用之前?如果需要更多信息,请告诉我!我只是不明白使用 await 不能解决这个问题。

标签: javascriptreactjsgoogle-cloud-firestore

解决方案


您不能在 useEffect 挂钩内将异步函数作为回调传递,因为它返回不允许的 Promise。只需尝试在 useEffect 中调用您的函数(但不要将回调函数定义为异步本身),然后在该函数内部执行您的异步任务......

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,但仍允许您执行所有异步任务


推荐阅读