To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function

后端 未结 6 894
无人及你
无人及你 2021-02-03 23:18

I have this code

import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route         


        
6条回答
  •  抹茶落季
    2021-02-03 23:23

    Folowing @Niyongabo solution, the way I ended up that fixed it was:

      const mountedRef = useRef(true);
    
      const fetchSpecificItem = useCallback(async () => {
        try {
          const ref = await db
            .collection('redeems')
            .where('rewardItem.id', '==', reward.id)
            .get();
          const data = ref.docs.map(doc => ({ id: doc.id, ...doc.data() }));
          if (!mountedRef.current) return null;
          setRedeems(data);
          setIsFetching(false);
        } catch (error) {
          console.log(error);
        }
      }, [mountedRef]);
    
      useEffect(() => {
        fetchSpecificItem();
        return () => {
          mountedRef.current = false;
        };
      }, [fetchSpecificItem]);
    

提交回复
热议问题