reactjs - '() =>() => Promise' türündeki argüman, 'EffectCallback' türündeki parametreye atanamaz


Benim kodum:

    useEffect(() => {
        document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
        window.$crisp.push(['do', 'chat:hide']);

        return async () => {
            window.$crisp.push(['do', 'chat:show']);
            document.querySelector('body').style['background-color'] = '#ffffff';
            if (router.query.id) {
                const resDoc = await firebase.firestore().doc(`documents/${router.query.id}`).get();
                if (resDoc.exists) {
                    await clearDocPrediction(router.query.id);
                }
            }
        };
    }, []);

Şimdi geri dönmemin nedeni, boşaltmada fonksiyon temizliği yaptığını düşündüğüm için buna ihtiyacım olması. Bu, nasıl çözeceğimden emin olmadığım bir tür derleme hatası. Her türlü yardım çok takdir edilecektir.

Cevap #1

Effect'in geri çağırma fonksiyonu void döndürmelidir, örneğin:

useEffect(() => { // callback; it returns void
  console.log("Hi")
}, [])

Veya

Bir () => void türünde bir temizlik (cleanup) fonksiyonu döndürmelidir, örneğin:

useEffect(() => {
  console.log("Hi")
  return () => { // cleanup function of type : () => void
    console.log("Cleanup")
  }
}, [])

Hatanın nedeni, kodunuzdaki temizleme işlevinin () => void türünde değil, () => Promise<void> türünde olmasıdır, örneğin:

'() =>() => Promise' türündeki argüman, 'EffectCallback' türündeki parametreye atanamaz. '() => Promise' türü, 'void | Destructor' türüne atanamaz.

useEffect(() => {
  console.log("Hi")
  return async () => { // WRONG
    console.log("Cleanup")
  }
}, [])

İşte bu nedenle, "temizleme" fonksiyonunuzu düzeltmek için nasıl yeniden düzenleyebileceğiniz:

return () => { // Remove async from here
  const clear = async () => { // Create a new async function: clear
    // write your cleanup code here
  };
  clear() // Call the clear() function
};

Cevap #2

useEffect geri çağrısının dönüş türü void olmalıdır. Yani bir Promise döndüremezsiniz:

useEffect(() => {
        document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
        window.$crisp.push(['do', 'chat:hide']);

        window.$crisp.push(['do', 'chat:show']);
        document.querySelector('body').style['background-color'] = '#ffffff';
        if (router.query.id) {
            firebase.firestore()
                .doc(`documents/${router.query.id}`)
                .get()
                .then((resDoc) => {
                    if (resDoc.exists) {
                        clearDocPrediction(router.query.id);
                    }
                });
        }
}, []);

İlgili makaleler