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

后端 未结 6 916
无人及你
无人及你 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条回答
  •  猫巷女王i
    2021-02-03 23:33

    fetchData is an async function which will return a promise. But you have invoked it without resolving it. If you need to do any cleanup at component unmount, return a function inside the effect that has your cleanup code. Try this :

    const Miliko = () => {
      const [data, setData] = useState({ hits: [] });
      const [url, setUrl] = useState('http://hn.algolia.com/api/v1/search?query=redux');
      const [isLoading, setIsLoading] = useState(false);
      const [isError, setIsError] = useState(false);
    
      useEffect(() => {
        (async function() {
          setIsError(false);
          setIsLoading(true);
          try {
            const result = await axios(url);
            setData(result.data);
          } catch (error) {
            setIsError(true);
          }
          setIsLoading(false);
        })();
    
        return function() {
          /**
           * Add cleanup code here
           */
        };
      }, [url]);
    
      return [{ data, isLoading, isError }, setUrl];
    };
    

    I would suggest reading the official docs where it is clearly explained along with some more configurable parameters.

提交回复
热议问题