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

后端 未结 6 895
无人及你
无人及你 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:31

    Without @windmaomao answer, I could spend other hours trying to figure out how to cancel the subscription.

    In short, I used two hooks respectively useCallback to memoize function and useEffect to fetch data.

      const fetchSpecificItem = useCallback(async ({ itemId }) => {
        try {
            ... fetch data
    
          /* 
           Before you setState ensure the component is mounted
           otherwise, return null and don't allow to unmounted component.
          */
    
          if (!mountedRef.current) return null;
    
          /*
            if the component is mounted feel free to setState
          */
        } catch (error) {
          ... handle errors
        }
      }, [mountedRef]) // add variable as dependency
    

    I used useEffect to fetch data.

    I could not call the function inside effect simply because hooks can not be called inside a function.

       useEffect(() => {
        fetchSpecificItem(input);
        return () => {
          mountedRef.current = false;   // clean up function
        };
      }, [input, fetchSpecificItem]);   // add function as dependency
    

    Thanks, everyone your contribution helped me to learn more about the usage of hooks.

提交回复
热议问题